第一步骤:首先开启qq邮箱的smtp服务,在个人邮箱,账户 设置中可以开启。
第二步骤:application.properties文件配置
spring.mail.host=smtp.qq.com
spring.mail.default-encoding=utf-8
spring.mail.username=xxx@qq.com(填写自己的qq邮箱就可以)
spring.mail.password=sryoocfhjiyebeje(这个填写自己qq邮箱的授权码就可以)
spring.mail.port=465(qq邮箱服务的端口号,465或者587都可以)
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true(这个是日志,可以在控制台看一些日志)
spring.thymeleaf.cache=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=html
第三步骤:
@Autowired
JavaMailSender javaMailSender;
@Autowired
TemplateEngine templateEngine;
@Test
void ceshi02() throws MessagingException {
MimeMessage msg = javaMailSender.createMimeMessage ( );
MimeMessageHelper helper = new MimeMessageHelper (msg, true);
helper.setSubject ("宁静大宝贝");
Context context=new Context ();
context.setVariable ("aihao", "喜欢吃猪蹄");
context.setVariable ("sex", "女孩");
context.setVariable ("username", "二丑");
context.setVariable ("age", "17");
String process = templateEngine.process ("hello.html", context);
第一个参数代表要引入的html的名字,第二个代表变量,这个变量中放html中的变量。
helper.setText (process,true);
helper.setFrom ("xxx@qq.com"); 代表发送人是谁
helper.setTo ("xxx@qq.com"); 代表收件人是谁
helper.setSentDate (new Date ());
javaMailSender.send (msg);
}
第四步骤:这是我写的html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
欢迎我家大宝贝<span th:text="${username}"></span>吃猪蹄!!
</div>
您的入职信息如下:
<table border="1">
<tr>
<td>爱好</td>
<td th:text="${aihao}"></td>
</tr>
<tr>
<td>性别</td>
<td th:text="${sex}"></td>
</tr>
<tr>
<td>年龄</td>
<td th:text="${age}"></td>
</tr>
</table>
<div style="color: chartreuse" >希望在未来的日子里,携手共进!!</div>
</body>
</html>
以上就完成了一次邮件发送!
注:由于个人新手原因,写的不是很好,有问题可以留言哈