Java 邮件发送

本文最后更新于:2024年9月8日 晚上

Java 邮件发送

Spring Boot

pom.xml

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

分析源码

  • 查看自动配置类:MailSenderAutoConfiguration
1
@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })
  • 这个类没有@Bean但是导入了MailSenderJndiConfiguration类,查看该类。
  • 这个类中存在@Bean,JavaMailSenderImpl
1
2
3
4
5
6
7
@Bean
JavaMailSenderImpl mailSender(Session session) {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setDefaultEncoding(this.properties.getDefaultEncoding().name());
sender.setSession(session);
return sender;
}
  • 查看MailProperties中的配置。
1
2
3
4
5
6
7
8
9
10
11
12
@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {
private static final Charset DEFAULT_CHARSET;
private String host;
private Integer port;
private String username;
private String password;
private String protocol = "smtp";
private Charset defaultEncoding;
private Map<String, String> properties;
private String jndiName;
}

配置邮件参数

1
2
3
4
5
spring.mail.username=123123@qq.com
spring.mail.password=你的qq授权码。
spring.mail.host=smtp.qq.com
# qq需要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true

测试

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
@Autowired
JavaMailSenderImpl mailSender;

@Test
public void contextLoads() {
// 一个简单的邮件。
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("通知1");
message.setText("今晚7:30开会");

message.setTo("123123@qq.com");
message.setFrom("456456@qq.com");
mailSender.send(message);
}

@Test
public void contextLoads2() throws MessagingException {
// 一个复杂的邮件。
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

helper.setSubject("通知2");
helper.setText("<b style='color:red'>今天 7:30来开会</b>",true);

// 发送附件。
helper.addAttachment("1.jpg",new File(""));
helper.addAttachment("2.jpg",new File(""));

helper.setTo("123123@qq.com");
helper.setFrom("456456@qq.com");

mailSender.send(mimeMessage);
}

commons-email

pom.xml

1
2
3
4
5
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>

MailUtil.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
public class MailUtil extends Thread {
private final String email;
private final String username;
private final String password;

public Mail(String username, String password, String email) {
this.username = username;
this.password= password;
this.email = email;
}

@Override
public void run() {
try {

HtmlEmail mail = new HtmlEmail();
// 设置邮箱服务器信息。
mail.setSslSmtpPort("25");
mail.setHostName("smtp.163.com");
// 设置密码验证器。
mail.setAuthentication("LuShan123888@163.com", "QVUYCXQRXBDARERD");
// 设置邮件发送者。
mail.setFrom("LuShan123888@163.com");
// 设置邮件接收者。
mail.addTo(email);
// 设置邮件编码。
mail.setCharset("UTF-8");
// 设置邮件主题。
mail.setSubject("Tally");
// 设置邮件内容。
mail.setHtmlMsg("<h1 style='color: red'>" + username + "注册成功 </h1>" + "请保存好密码:"+password);
// 设置邮件发送时间。
mail.setSentDate(new Date());
// 发送邮件。
mail.send();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public static void main(String[] args) {
Mail mail = new Mail("test","123123","test@qq.com");
}
}

QQ 邮箱

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
public class MailUtil extends Thread {
private final String from = "1074544350@qq.com";
private final String checkCode = "wnozaopvasqigchb";
private final String email;

public QQMail(String username, String password, String email) {
this.email = email;
}

@Override
public void run() {
try {
Properties prop = new Properties();
String host = "smtp.qq.com";
prop.setProperty("mail.host", host);// 设置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对象。
//QQ邮箱才有,其他不用。
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
// 发件人的邮件用户名,授权码。
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, checkCode);
}
});
// 开启Session的debug模式。
session.setDebug(true);
//2.通过Session得到transport对象。
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器。
ts.connect(host, from, checkCode);
//4.创建邮件。
// 注意需要传递Session
MimeMessage mimeMessage = new MimeMessage(session);

// 指明邮件的发件人。
mimeMessage.setFrom(new InternetAddress(from));
// 指明邮件的收件人。
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 邮件的标题。
mimeMessage.setSubject("Test");
// 邮件的文本内容。

// 简单邮件。
// mimeMessage.setContent("<h1 style='color: red'>" + username + "注册成功 </h1>" + "请保存好密码:" + password, "text/html;charset=UTF-8");

// mimeMessage.saveChanges();
// 复杂邮件。
// 准备图片数据。
MimeBodyPart image = new MimeBodyPart();
// 图片需要经过数据处理。
DataHandler dataHandler = new DataHandler(new FileDataSource("/Users/cian/Code/Study/Java/JavaWeb/src/main/resources/1.jpg"));
image.setDataHandler(dataHandler);// 在Body中放入这个处理的图片数据。
image.setContentID("1.jpg");// 给图片设置一个ID,我们在后面可以使用。
// 准备正文数据。
MimeBodyPart text = new MimeBodyPart();
//setContentId=cid
text.setContent("这是一封邮件正文带图片<img width=\"400px\" src='cid:1.jpg'>的邮件", "text/html;charset=UTF-8");
// 描述数据关系。
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");// 拼接。
// 设置到消息中,保存修改。
mimeMessage.setContent(mm);
mimeMessage.saveChanges();
//5.发送邮件。
ts.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
//6.关闭连接。
ts.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public static void main(String[] args) {
MailUtil mail = new MailUtil("test", "123456", "1074544350@qq.com");
mail.start();
}
}