Skip to content

邮件发送结合Thymeleaf渲染模板

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

编写模版 example.html

html
<!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

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 {
           //构造上下文(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/

最近更新