1 package com.hrj;
 2 
 3 import com.sun.mail.util.MailSSLSocketFactory;
 4 
 5 import javax.mail.*;
 6 import javax.mail.internet.InternetAddress;
 7 import javax.mail.internet.MimeMessage;
 8 import java.net.InetAddress;
 9 import java.security.GeneralSecurityException;
10 import java.util.Properties;
11 
12 public class MailDemo01 {
13     public static void main(String[] args) throws GeneralSecurityException, MessagingException {
14         // 授权码: ??
15         Properties prop = new Properties();
16         prop.setProperty("mail.host", "smtp.qq.com");
17         prop.setProperty("mail.transport.protocol", "smtp");
18         prop.setProperty("mail.smtp.auth", "true");
19 
20         // 关于 QQ 邮箱, 还要设置 SSL 加密, 加上以下代码即可
21         MailSSLSocketFactory sf = new MailSSLSocketFactory();
22         sf.setTrustAllHosts(true);
23         prop.put("mail.smtp.ssl.enable", "true");
24         prop.put("mail.smtp.ssl.socketFactory", sf);
25 
26 
27         // =================== 使用 JavaMail 发送邮件的5个步骤 =================== //
28         // 1. 创建定义整个应用程序所需的环境信息的 Session 对象
29         Session session = Session.getDefaultInstance(prop, new Authenticator(){
30             public PasswordAuthentication getPasswordAuthentication() {
31                 // 发件人邮件用户名, 密码
32                 return new PasswordAuthentication("2191313025@qq.com", "??");
33             }
34         });
35 
36         // 开启 session 的 debug 模式
37         session.setDebug(true);
38 
39         // 2. 通过 session 获得 transport 对象
40         Transport transport = session.getTransport();
41 
42         // 3. 使用邮箱的用户名 和 授权码连接上邮件服务器
43         transport.connect("smtp.qq.com", "2191313025@qq.com", "??");
44 
45         // 4. 创建邮件
46         MimeMessage message = new MimeMessage(session);
47         message.setFrom(new InternetAddress("2191313025@qq.com"));  // 指明邮件发送人
48         message.setRecipient(Message.RecipientType.TO, new InternetAddress("2191313025@qq.com"));  // 指明接收人
49         message.setSubject("欢迎来到西部开源学习 Java");  // 邮件标题
50         message.setContent("滴滴滴, 你好啊!", "text/html;charset=UTF-8");
51 
52         // 5. 发送邮件
53         transport.sendMessage(message, message.getAllRecipients());
54 
55         // 6. 关闭连接
56         transport.close();
57 
58 
59     }
60 
61 }