SpringBoot发送电子邮件
- application.properties文件中配置如下:
spring.mail.host=smtp.qq.com
spring.mail.username=33442422424@qq.com #发送方QQ邮箱
spring.mail.password=dsfdsffsdfsdfsddas #邮箱授权码
spring.mail.default-encoding=UTF-8
- 生成邮件
private Employee employee;
private JavaMailSender javaMailSender;
private TemplateEngine templateEngine;
public void sendMessage(){
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(employee.getEmail());
helper.setFrom("133333145657@qq.com");
helper.setSubject("XX集团:通知");
Context ctx = new Context();
ctx.setVariable("name", employee.getName());
ctx.setVariable("workID", employee.getWorkID());
ctx.setVariable("contractTerm", employee.getContractTerm());
ctx.setVariable("beginContract", employee.getBeginContract());
ctx.setVariable("endContract", employee.getEndContract());
ctx.setVariable("departmentName", employee.getDepartmentName());
ctx.setVariable("posName", employee.getPosName());
String mail = templateEngine.process("email.html", ctx);
helper.setText(mail, true);
javaMailSender.send(message);
} catch (MessagingException e) {
System.out.println("发送失败");
} catch (javax.mail.MessagingException e) {
e.printStackTrace();
}
}
- html模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>你好,
<span th:text="${name}"></span>童鞋,欢迎加入XX大家庭!您的入职信息如下:</p>
<table border="1" cellspacing="0">
<tr>
<td><strong style="color: #F00">工号</strong></td>
<td th:text="${workID}"></td>
</tr>
<tr>
<td><strong style="color: #F00">合同期限</strong></td>
<td th:text="${contractTerm}+'年'"></td>
</tr>
<tr>
<td><strong style="color: #F00">合同起始日期</strong></td>
<td th:text="${#dates.format(beginContract, 'yyyy-MM-dd')}"></td>
</tr>
<tr>
<td><strong style="color: #F00">合同截至日期</strong></td>
<td th:text="${#dates.format(endContract, 'yyyy-MM-dd')}"></td>
</tr>
<tr>
<td><strong style="color: #F00">所属部门</strong></td>
<td th:text="${departmentName}"></td>
</tr>
<tr>
<td><strong style="color: #F00">职位</strong></td>
<td th:text="${posName}"></td>
</tr>
</table>
<p>
<strong style="color: #F00; font-size: 24px;">
希望在未来的日子里,携手共进!
</strong>
</p>
</body>
</html>