参考实现代码:
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 { 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/
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏