Java實現郵件發送的具體代碼,供大家參考,具體內容如下
一、郵件服務器與傳輸協議
要在網絡上實現郵件功能,必須要有專門的郵件服務器。這些郵件服務器類似于現實生活中的郵局,它主要負責接收用戶投遞過來的郵件,并把郵件投遞到郵件接收者的電子郵箱中。
SMTP服務器地址:一般是 smtp.xxx.com,比如163郵箱是smtp.163.com,qq郵箱是smtp.qq.com。
SMTP協議
通常把處理用戶smtp請求(郵件發送請求)的服務器稱之為SMTP服務器(郵件發送服務器)。
POP3協議
通常把處理用戶pop3請求(郵件接收請求)的服務器稱之為POP3服務器(郵件接收服務器)。
二、Java發送郵件
使用到的jar包:
- mail.jar
- activation.jar
QQ郵箱需獲取相應的權限:
QQ郵箱–>郵箱設置–>賬戶–>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務 開啟POP3/SMTP服務,然后獲取16位授權碼(注意不要將授權碼泄露,一個賬戶可以擁有多個授權碼)
Java實現純文本郵件發送
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
package org.westos.email; import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.security.GeneralSecurityException; import java.util.Properties; public class SendEamil { public static void main(String[] args) throws MessagingException, GeneralSecurityException { //創建一個配置文件并保存 Properties properties = new Properties(); properties.setProperty( "mail.host" , "smtp.qq.com" ); properties.setProperty( "mail.transport.protocol" , "smtp" ); properties.setProperty( "mail.smtp.auth" , "true" ); //QQ存在一個特性設置SSL加密 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts( true ); properties.put( "mail.smtp.ssl.enable" , "true" ); properties.put( "mail.smtp.ssl.socketFactory" , sf); //創建一個session對象 Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { } }); //開啟debug模式 session.setDebug( true ); //獲取連接對象 Transport transport = session.getTransport(); //連接服務器 //創建郵件對象 MimeMessage mimeMessage = new MimeMessage(session); //郵件發送人 //郵件接收人 //郵件標題 mimeMessage.setSubject( "Hello Mail" ); //郵件內容 mimeMessage.setContent( "我的想法是把代碼放進一個循環里" , "text/html;charset=UTF-8" ); //發送郵件 transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); //關閉連接 transport.close(); } } |
Java實現文本圖片附件復雜的郵件發送
MIME(多用途互聯網郵件擴展類型)
MimeBodyPart類
javax.mail.internet.MimeBodyPart類 表示的是一個MIME消息,它和MimeMessage類一樣都是從Part接口繼承過來。
MimeMultipart類
javax.mail.internet.MimeMultipart是抽象類 Multipart的實現子類,它用來組合多個MIME消息。一個MimeMultipart對象可以包含多個代表MIME消息的MimeBodyPart對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
package org.westos.email; import com.sun.mail.util.MailSSLSocketFactory; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.security.GeneralSecurityException; import java.util.Properties; public class SendComplexEmail { public static void main(String[] args) throws GeneralSecurityException, MessagingException { Properties prop = new Properties(); prop.setProperty( "mail.host" , "smtp.qq.com" ); 設置QQ郵件服務器 prop.setProperty( "mail.transport.protocol" , "smtp" ); // 郵件發送協議 prop.setProperty( "mail.smtp.auth" , "true" ); // 需要驗證用戶名密碼 // QQ郵箱設置SSL加密 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts( true ); prop.put( "mail.smtp.ssl.enable" , "true" ); prop.put( "mail.smtp.ssl.socketFactory" , sf); //1、創建定義整個應用程序所需的環境信息的 Session 對象 Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { //傳入發件人的姓名和授權碼 } }); //2、通過session獲取transport對象 Transport transport = session.getTransport(); //3、通過transport對象郵箱用戶名和授權碼連接郵箱服務器 //4、創建郵件,傳入session對象 MimeMessage mimeMessage = complexEmail(session); //5、發送郵件 transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); //6、關閉連接 transport.close(); } public static MimeMessage complexEmail(Session session) throws MessagingException { //消息的固定信息 MimeMessage mimeMessage = new MimeMessage(session); //發件人 //收件人 //郵件標題 mimeMessage.setSubject( "帶圖片和附件的郵件" ); //郵件內容 //準備圖片數據 MimeBodyPart image = new MimeBodyPart(); DataHandler handler = new DataHandler( new FileDataSource( "E:\\IdeaProjects\\WebEmail\\resources\\測試圖片.png" )); image.setDataHandler(handler); image.setContentID( "test.png" ); //設置圖片id //準備文本 MimeBodyPart text = new MimeBodyPart(); text.setContent( "這是一段文本<img src='cid:test.png'>" , "text/html;charset=utf-8" ); //附件 MimeBodyPart appendix = new MimeBodyPart(); appendix.setDataHandler( new DataHandler( new FileDataSource( "E:\\IdeaProjects\\WebEmail\\resources\\測試文件.txt" ))); appendix.setFileName( "test.txt" ); //拼裝郵件正文 MimeMultipart mimeMultipart = new MimeMultipart(); mimeMultipart.addBodyPart(image); mimeMultipart.addBodyPart(text); mimeMultipart.setSubType( "related" ); //文本和圖片內嵌成功 //將拼裝好的正文內容設置為主體 MimeBodyPart contentText = new MimeBodyPart(); contentText.setContent(mimeMultipart); //拼接附件 MimeMultipart allFile = new MimeMultipart(); allFile.addBodyPart(appendix); //附件 allFile.addBodyPart(contentText); //正文 allFile.setSubType( "mixed" ); //正文和附件都存在郵件中,所有類型設置為mixed //放到Message消息中 mimeMessage.setContent(allFile); mimeMessage.saveChanges(); //保存修改 return mimeMessage; } } |
JavaWeb發送郵件(網站注冊成功發送提示郵件)
1.User
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
package org.westos.mail; public class User { private String name; private String password; private String mail; public User() { } public User(String name, String password, String mail) { this .name = name; this .password = password; this .mail = mail; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getPassword() { return password; } public void setPassword(String password) { this .password = password; } public String getMail() { return mail; } public void setMail(String mail) { this .mail = mail; } @Override public String toString() { return "User{" + "name='" + name + '\ '' + ", password='" + password + '\ '' + ", mail='" + mail + '\ '' + '}' ; } } |
2.Servlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package org.westos.mail; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class Servlet extends javax.servlet.http.HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) { //處理前端請求 String username = request.getParameter( "username" ); String password = request.getParameter( "password" ); String email = request.getParameter( "email" ); //將信息封裝進user對象 User user = new User(username, password, email); SendMail sendMail = new SendMail(user); sendMail.start(); //開啟線程 request.setAttribute( "msg" , "發送成功" ); try { request.getRequestDispatcher( "msg.jsp" ).forward(request,response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
3.SengMail
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
package org.westos.mail; import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.security.GeneralSecurityException; import java.security.PublicKey; import java.util.Properties; public class SendMail extends Thread { //發件人信息 //發件人郵箱 //郵箱密碼 private String password = "16位授權碼" ; //郵件發送的服務器 private String host = "smtp.qq.com" ; //收件人信息 private User user; public SendMail(User user){ this .user = user; } @Override public void run() { try { Properties properties = new Properties(); properties.setProperty( "mail.host" , "smtp.qq.com" ); properties.setProperty( "mail.transport.protocol" , "smtp" ); properties.setProperty( "mail.smtp.auth" , "true" ); //QQ存在一個特性設置SSL加密 MailSSLSocketFactory sf = null ; try { sf = new MailSSLSocketFactory(); } catch (GeneralSecurityException e) { e.printStackTrace(); } sf.setTrustAllHosts( true ); properties.put( "mail.smtp.ssl.enable" , "true" ); properties.put( "mail.smtp.ssl.socketFactory" , sf); //創建一個session對象 Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(recipient,password); } }); //開啟debug模式 session.setDebug( true ); //獲取連接對象 Transport transport = null ; try { transport = session.getTransport(); } catch (NoSuchProviderException e) { e.printStackTrace(); } //連接服務器 transport.connect(host,From,password); //創建一個郵件發送對象 MimeMessage mimeMessage = new MimeMessage(session); //郵件發送人 mimeMessage.setFrom( new InternetAddress(recipient)); //郵件接收人 mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getMail())); //郵件標題 mimeMessage.setSubject( "網站注冊成功" ); //郵件內容 mimeMessage.setContent( "網站注冊成功,密碼為" +user.getPassword()+ ",請妥善保管密碼" , "text/html;charset=UTF-8" ); //發送郵件 transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); transport.close(); } catch (Exception e){ e.printStackTrace(); } } } |
4.register.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<%@ page contentType="text/html;charset=UTF-8" language="java" %> < html > < head > < title >注冊頁面</ title > </ head > < body > < form action = "${pageContext.request.contextPath}/a.do" method = "post" > < p >用戶名:< input type = "text" name = "username" required></ p > < p >密碼:< input type = "password" name = "password" required></ p > < p >郵箱:< input type = "email" name = "email" required></ p > < p >< input type = "submit" value = "提交" ></ p > </ form > </ body > </ html > |
5.msg.jsp
1
2
3
4
5
6
7
8
9
|
<%@ page contentType="text/html;charset=UTF-8" language="java" %> < html > < head > < title >Title</ title > </ head > < body > ${msg} </ body > </ html > |
6.web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<? xml version = "1.0" encoding = "UTF-8" ?> < web-app xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version = "4.0" > < servlet > < servlet-name >Servlet</ servlet-name > < servlet-class >org.westos.mail.Servlet</ servlet-class > </ servlet > < servlet-mapping > < servlet-name >Servlet</ servlet-name > < url-pattern >/a.do</ url-pattern > </ servlet-mapping > </ web-app > |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/baolingye/article/details/96598222