springboot发送邮件,内容使用thymeleaf模板引擎排版

springboot发送邮件,内容使用thymeleaf模板引擎排版

      • 1、导入jar包
      • 2、yml设置
      • 3、收件人以及收件信息设置
      • 4、发邮件service
      • 5、模版页面
      • 6、controller

1、导入jar包

<!--发送邮件-->
  <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-mail</artifactId>
   </dependency>
<!--使用thymeleaf 形式-->
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-thymeleaf</artifactId>
   </dependency>

2、yml设置

发件邮箱信息设置:


spring:
  mail:
    host: smtp.xx.cn
    port: 465
    username: 你的邮箱
    password: 你的密码
#    default-encoding: UTF-8
    protocol: smtp
    properties: # 配置以SSL的方式发送, 这个需要使用这种方式并且端口是465
      mail:
        smtp:
          auth: true
          ssl:
            enable: true
            socketFactory:
              class: com.sun.mail.util.MailSSLSocketFactory
              fallback: false
        debug: true

3、收件人以及收件信息设置

@Getter
@Setter
public class AcceptMailParam {
    //标题
    private String title;
    //接收人邮件地址
    private String receiveEmail[];
    //抄送人邮件地址
    private String chaoSongPersonEmail[];
    
    //附件,value 文件的绝对地址/动态模板数据
    private Map<String, Object> attachment;
	
	//thymeleaf模版引擎页面对象数据:邮件排版内存
    List<OperateDataResultInfoView> pageViewList;
}

页面对象数据展示
@Setter
@Getter
public class OperateDataResultInfoView {

    private Long id;

    /**
     * 存储当前年月,eg:202301
     */
    private Integer curMonth;
    /**
     * 库名
     */
    private String dbName;
    /**
     * 表名
     */
    private String tableName;

    /**
     * 计划生成数据量
     */
    private Long planGenDataCnt;

    /**
     * 实际生成数据量
     */
    private Long actualGenDataCnt;

    /**
     * 备注
     */
    private String remark;

    private String gmtCreate;

    private String gmtModified;

    /* *
     * 剩余待生成数据量
     */
    private Long remainToGenCnt;

    /* *
     * 生成数据成功率(实际生成数量/计划生成数量),单位%
     */
    private BigDecimal genDataSuccessRate;

/**模拟生成数据*/
    public OperateDataResultInfoView() {

        this.id = ThreadLocalRandom.current().nextLong(100L, 999L);
        this.curMonth = DateUtil.getPreMonth();
        String[] dbAndTableName = ("dbName" + id + ".tableName" + id).split("\\.");
        this.dbName = dbAndTableName[0];
        this.tableName = dbAndTableName[1];
        this.planGenDataCnt = id + ThreadLocalRandom.current().nextLong(10L, 99L);
        this.actualGenDataCnt = id;
        this.remark = null;
        this.gmtCreate = DateUtil.getNowStr();
        this.gmtModified = DateUtil.getNowStr();
        this.remainToGenCnt = (planGenDataCnt - actualGenDataCnt) >= 0 ? (planGenDataCnt - actualGenDataCnt) : 0;

        BigDecimal rate = new BigDecimal(actualGenDataCnt).divide(new BigDecimal(planGenDataCnt), 4, BigDecimal.ROUND_HALF_UP);
        this.genDataSuccessRate = rate.compareTo(new BigDecimal("1")) >= 0 ? new BigDecimal("100") : rate.multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);
    }
}

4、发邮件service

public interface SendMailService {
    /**
     * 邮件内容排版调试
     */
    AcceptMailParam getMailContentAndSendMail(Integer curMonth);
}

/**
     * 获取指定月份的邮件【邮件内容:生成数据的结果集 信息】
     * 次月1日8点 发送
     */
    @Override
    public AcceptMailParam getMailContentAndSendMail(Integer curMonth) {
        AcceptMailParam acceptMailParam = new AcceptMailParam();
        List<OperateDataResultInfoView> pageViewList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            pageViewList.add(new OperateDataResultInfoView());
        }
        Collections.sort(pageViewList, Comparator.comparing(OperateDataResultInfoView::getId).reversed());
        acceptMailParam.setPageViewList(pageViewList);

        String[] emails = {"[email protected]"};
        String[] chaoSongPerson = {"[email protected]"};
        //收件人,支持多人
        acceptMailParam.setReceiveEmail(emails);
        //抄送人,支持多人
        acceptMailParam.setChaoSongPersonEmail(chaoSongPerson);
        acceptMailParam.setTitle("统计业务表生成数据结果");

        //添加附件
        Map<String, Object> map = new HashMap<>();
        //key为邮件附件文件名称,路径改为你的服务器路径即可,可添加不同类型文件
        map.put("1-test1.zip", "/Users/gina/xx/data/test2.zip");
        map.put("2-test2.xlsx", "/Users/gina/xx/data/test1.xlsx");
        acceptMailParam.setAttachment(map);
        
        //调试邮件内容排版时,此处可注释掉。
        //this.sendTemplateMail(acceptMailParam,"/mail/list");
        return acceptMailParam;
    }

5、模版页面

在resources下,在路径templates/mail/下添加文件list.html

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<style>
  tr.odd td {
    background-color: #f0faaa;
  }

  td.number {
    text-align: right;
  }


  table {
    width: 100%;
    border: 1px solid #000;
    border-collapse: collapse;
  }

  table > tbody > tr > td, table > thead > tr > th {
    padding: 2px 10px;
    border-left: 1px dotted #000000;
    vertical-align: top;
    line-height: 20px;
  }

  table > tbody > tr, table > thead > tr {
    border-bottom: 1px solid #000000;
  }

  table th {
    background-color: #99cc33;
  }

  table > tbody > tr > td > a, table > tbody > tr > td > a:hover {
    text-decoration: none;
    font-weight: bold;
    background-color: #352726;
    padding: 2px 10px;
    color: #f0faaa;
    margin-left: 10px;
    text-transform: uppercase;
    border: 0px;
  }

</style>
  <head>
    <title>统计业务表生成数据结果</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <h1>统计业务表生成数据结果</h1>
    <table>
      <tr>
        <th>生成月份</th>
        <th>库名</th>
        <th>表名</th>
        <th>计划生成()</th>
        <th>实际生成()</th>
        <th>成功率%</th>
        <th>未生成()</th>
        <th>创建时间</th>
        <th>更新时间</th>
        <th>备注</th>
      </tr>
      <tr th:each="o : ${pageViewList}" th:class="${o.id % 2 == 0}? 'odd'" >
        <td th:text="${o.curMonth}"   ></td>
        <td th:text="${o.dbName}" ></td>
        <td th:text="${o.tableName}" ></td>
        <td th:text="${o.planGenDataCnt}" ></td>
        <td th:text="${o.actualGenDataCnt}"></td>
        <td th:text="${o.genDataSuccessRate}"></td>
        <td th:text="${o.remainToGenCnt}"></td>
        <td th:text="${o.gmtCreate}"></td>
        <td th:text="${o.gmtModified}"></td>
        <td th:text="${o.remark}"></td>
      </tr>
    </table>
  </body>
</html>

6、controller

@Controller
@Slf4j
public class SendMailController {

    /**
     * 调试生成的页面样式,不发邮件
     * 数据处理结果集view
     */
    @Resource
    private SendMailService sendMailService;

    /** 点此可直接访问
     * http://localhost:8081/sendMail?curMonth=202311
    */
    @RequestMapping("sendMail")
    public String sendMail(Model model, @RequestParam(name = "curMonth") Integer curMonth) {
        try {
            AcceptMailParam acceptMailParam = sendMailService.getMailContentAndSendMail(curMonth);
            model.addAttribute("title", acceptMailParam.getTitle());
            model.addAttribute("pageViewList", acceptMailParam.getPageViewList());
        } catch (Exception e) {
            log.error("sendMail fail ,msg={}", e.getMessage());
        }
        return "mail/list";
    }
}

7、启动服务后,访问页面展示:

邮箱内容样式为:
springboot发送邮件,内容使用thymeleaf模板引擎排版_第1张图片

有对thymeleaf感兴趣的同学可通过中文官网去了解:thymeleaf中文官网

你可能感兴趣的:(关于测试,后端,springboot+发邮件,thymeleaf)