参考实现代码:
https://github.com/ityouknow/spring-boot-examples/blob/master/spring-boot-mail/src/test/java/com/neo/service/MailServiceTest.java
编写模版example.html
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
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>
发送类实现SendMailServiceImpl.java
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 {
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/