1.获取QQ邮箱授权码
邮箱设置–>账户–>POP3/SMTP服务开启
2.导入spring mail 和thymeleaf jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<!-- thymeleaf模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.在application.properties配置mail
# 访问邮箱的域名 smtp表示协议
spring.mail.host=smtp.qq.com
spring.mail.username=*******@qq.com
#授权码
spring.mail.password=***********
spring.mail.protocol=smtps
# 采用ssl安全连接
spring.mail.properties.mail.smtp.ssl.enable=true
4.编辑发送邮件的工具类
@Component
public class MailClient {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
public void sendMail(String to, String subject, String content) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
//第二个参数为true表示邮件正文是html格式的,默认是false
helper.setText(content, true);
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
e.getMessage();
}
}
}
5.编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {
@Autowired
private MailClient mailClient;
@Autowired
private TemplateEngine templateEngine;
@Test
public void testTextMail() {
mailClient.sendMail("**********@qq.com", "TEST", "Welcome.");
}
//发送html页面
@Test
public void testHtmlMail() {
Context context = new Context();
context.setVariable("username", "*****");
//第一个参数为templates目录下的要发送html文件的相对路径
String content = templateEngine.process("/mail/demo", context);
System.out.println(content);
mailClient.sendMail("*********@qq.com", "HTML", content);
}
}
要发送的html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Welcome,<span style="color: aqua" th:text="${username}"></span></h1>
</body>
</html>