fzy-blog

邮件发送结合Thymeleaf渲染模板

2019-05-24

参考实现代码:
https://github.com/ityouknow/spring-boot-examples/blob/master/spring-boot-mail/src/test/java/com/neo/service/MailServiceTest.java

编写模版 example.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<h1>邮件主题</h1>
<ul>
<li th:text="${email.subject}">科帮网</li>
<li th:text="${email.content}">充值成功</li>
<li th:text="${email.kvMap.key}">这是个钥匙</li>
</ul>
</body>
</html>
</html>

发送类实现 SendMailServiceImpl.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
public class SendMailServiceImpl implements ISendMailService {
private static final Logger LOG = LogManager.getLogger(SendMailServiceImpl.class.getName());
@Autowired
private SpringTemplateEngine templateEngine;
@Override
public String sendMail(MailParameter params) {
String message = Constants.SUCCESS;
try {
//构造上下文(Model)
Context context = new Context();
context.setVariable("email", params);
//构造静态文件地址
String result = UUID.randomUUID().toString()+".html";
FileWriter write = new FileWriter(Constants.TEMP+result);
//构造模板引擎并渲染
templateEngine.process(params.getTemplate(), context, write);
params.setTemplate(result);
message = MailUtil.sendEmail(params);
} catch (Exception e) {
LOG.error("邮件:{} 发送异常{}",params.getEmail(),e);
message = Constants.FAIL;
}
return message;
}
}

当然这里只是提供了部分代码实现,比如实体类,邮件发送工具类并未罗列。还有就是关于 Thymeleaf 标签的一些实用说明,网上很多,请自行百度。

来源: https://blog.52itstyle.com/archives/1089/

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章