springboot系列13: 邮件模版

 在生活中我们经常会遇到,注册完网站后会收到一份邮件,只有当我们点击了邮件中的激活链接才能正常登录网站。

邮件模版通常如下:

尊敬的XXX用户:
              
          恭喜您注册成为xxx网的用户,同时感谢您对xxx的关注与支持,请点击“激活认证”。

 这里用户名和激活链接是变化的,其他邮件内容均不变,如果每次发送邮件都需要手动拼接的话会不够优雅,并且每次模板的修改都需要改动代码的话也很不方便,因此对于这类邮件需求,都建议做成邮件模板来处理。模板的本质很简单,就是在模板中替换变化的参数,转换为 html 字符串即可,这里以thymeleaf为例。

1、pom配置thymeleaf 包

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

2、创建模版        

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>激活验证</title>
    </head>
    <body>
        您好,这是验证邮件,请点击下面的链接完成验证,<br/>
        <a href="#" th:href="@{ http://www.zlcxy.top/user/jihuo/{id}(id=${id}) }">激活账号</a>
    </body>
</html>

 

3、解析模版并发送

    @Override
    public void sendTemplateMail(String to, String subject,Map<String,Object> map) {
        //创建邮件正文
        Context context = new Context();
        for (Map.Entry<String,Object>  entry :  map.entrySet()) {
            context.setVariable(entry.getKey(), entry.getValue());
        }
        String emailContent = templateEngine.process("emailTemplate", context);
        sendHtmlMail(to,subject,emailContent);
    }

 

4、测试邮件模版

    @Test
    public void testTemplateMail() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("id","001");
        mailService.sendTemplateMail("1796969389@qq.com","test template mail", map);
    }

 

5、运行结果

 

2020-06-12 07:59:59.315  INFO 7728 --- [           main] c.example.service.impl.MailServiceImpl   : html邮件发送成功

 

6、重试机制

   生产中,会因各种原因导致邮件发送失败,例如:邮件发送过于频繁,网络异常等。这种情况下,我们需要考虑邮件发送的重试机制。

实现思路:

1、发送邮件前记录数据库,并登记发送状态为未发送。
2、调用发送邮件接口,将结果更新发送状态。
3、定时任务扫描结果状态为失败的,且重试次数小于3,每次重试将更新重试次数值。

 

7、异步机制

      很多时候发送邮件并不是我们的主要的关注的业务,如通知类、提醒类邮件发送,这些可以允许延时或失败,可以采用异步发送,加快主交易执行速度。实际项目中可以采用MQ等第三方中间件来做异步机制处理。

 

posted @ 2022-01-13 19:33  IT6889  阅读(479)  评论(0编辑  收藏  举报