1.为什么要写这一篇呢?

在做一个邮件发送功能的时候,需要发送html邮件,javaMail 发送html 的时候需要有已经生成的html正文,所以需要提前将要发送的内容生成,所以就需要模板引擎来动态填充数据。

public void sendHtmlEmail(String to, String object, String content) {
MimeMessage message = mailSender.createMimeMessage();//创建一个MINE消息 try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(object);
helper.setText(content, true); mailSender.send(message);
log.info("html邮件发送成功");
} catch (MessagingException e) {
log.error("发送html邮件时发生异常!", e);
}
}

2.引入依赖

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

ognl 的jar包可能并不需要,在生成过程中报classNotFound ,应该是和我的项目结构有关系,这个包根据实际情况来使用

 <dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.2</version>
</dependency>

3.代码

(1)首先准备一个html模板,需要替换的内容使用themleaf的th表达式来占位。我的工程是springboot 项目,文件位置放在resources/templates,也就是classpath:templates/

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<html>
<head>
<title>Title</title>
<style type="text/css">
td{
width: 80px;
height: 25px;
align-content: center;
}
</style>
</head>
<body>
<h4>亲爱的<span th:text="${name}"></span>,您<span th:text="${month}"></span>月份的工资如下:</h4>
<table border="1" style="border-collapse: collapse" >
<tr>
<td th:each="item:${th}" th:text="${item}"></td>
</tr>
<tr>
<td th:each="ib:${tb}" th:text="${ib}"></td>
</tr>
</table>
</body>
</html>

2.配置模板引擎

@Configuration
public class MailConfig { @Bean("myTemplateEngine")
public TemplateEngine templateEngine(){
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/");
resolver.setSuffix(".html");
TemplateEngine engine = new TemplateEngine();
engine.setTemplateResolver(resolver);
return engine;
}
}

为手动生成html文件单独定义一个模板引擎,其他的使用默认配置。其中制定了模板文件的位置及后缀名,这个配置和application.properties 中配置是一样的

3.生成html

 @PostMapping("/sendEmail")
@ResponseBody
public AjaxResult sendEmail(Integer id) throws IOException {
List<ComponentVo> componentVos = salaryCompnentService.selectComponentSum(id);
List<String> th = Lists.newArrayList();
List<String> tb = Lists.newArrayList();
for (int i = 0; i < componentVos.size(); i++) {
ComponentVo vo = componentVos.get(i);
th.add(i, vo.getName());
tb.add(i, vo.getAmount());
}
SalaryCalculateVo salaryCalculate = salaryService.selectSalaryById(id);
Context context = new Context();
context.setVariable("name", salaryCalculate.getEmpName());
context.setVariable("month", salaryCalculate.getWorkMonth());
context.setVariable("th", th);
context.setVariable("tb", tb); String res = engine.process("mailTeamlate", context);
salaryService.sendEmail(id,res, salaryCalculate.getWorkMonth() + "工资条", salaryCalculate.getEmail());
return toAjax(1);
}

由于是测试功能,没有在代码结构上下功夫,随便写一下。主要的代码是王模板上下文Context中填充参数,engine.process()有很多重载的方法,主要有两类,一类是直接输出内容,一类是将文件输出到指定文件里。String template 这个参数指的是模板的名称。比如我的叫mailTeamlate,解析的时候模板引擎会找classpath:templates/mailTeamlate.html 这个文件。

 public final String process(String template, IContext context) {
return this.process(new TemplateSpec(template, (Set)null, (TemplateMode)null, (String)null, (Map)null), context);
}
 public final void process(String template, IContext context, Writer writer) {
this.process(new TemplateSpec(template, (Set)null, (TemplateMode)null, (String)null, (Map)null), context, writer);
}

4.效果

具体的文件内容就不说了,直接看我放到邮件的里面正文里的html样式

使用Themleaf 模板引擎手动生成html文件的更多相关文章

  1. SpringBoot获取Freemarker模板引擎,生成HTML代码

    今天用Ajax异步添加评论,加载Freemarker模板引擎,生成模板模块 1.新建Freemarker模板 <li id="${comment.oId}"> < ...

  2. 使用 Velocity 模板引擎快速生成代码(zhuan)

    http://www.ibm.com/developerworks/cn/java/j-lo-velocity1/ ****************************************** ...

  3. 使用Velocity 模板引擎快速生成代码

    Velocity 模板引擎介绍 在现今的软件开发过程中,软件开发人员将更多的精力投入在了重复的相似劳动中.特别是在如今特别流行的MVC架构模式中,软件各个层次的功能更加独立,同时代码的相似度也更加高. ...

  4. 使用VTemplate模板引擎动态生成订单流程图

    1.VTemplate模板引擎的简介 VTemplate模板引擎也简称为VT,是基于.NET的模板引擎,它允许任何人使用简单的类似HTML语法的模板语言来引用.NET里定义的对象.当VTemplate ...

  5. Java使用 VelocityEngine模板引擎快速生成HTML等各种代码

    https://blog.csdn.net/icannotdebug/article/details/79725297 一.简介 Velocity 是一个基于 Java 的模板引擎框架,提供的模板语言 ...

  6. 手动生成moc文件

    在VS中写Qt项目时,手动添加了一个类,由于要用到信号槽,所以需要生成相应的moc文件.写好信号槽以后,在类里面第一行应该写上Q_OBJECT关键字,编译项目会提示无法找到moc_XXX.cpp文件. ...

  7. 由动态库文件dll生成lib库文件(手动生成.def文件,然后使用lib命令编译,非常牛),同理可使用dll生成.a库文件

    本文基于OpenBlas的编译和安装,来说明如何从一个dll文件生成lib库文件. 参考OpenBlas的说明“Howto generate import library for MingW”,和Mi ...

  8. WebApi中利用Razor模板引擎来生成html

    在服务器端基于Razor来生成html的一个思路 using System.Web.Mvc; using System.IO; using System.Web.Routing; using Syst ...

  9. 转: 使用 Velocity 模板引擎快速生成代码

    from:https://www.ibm.com/developerworks/cn/java/j-lo-velocity1/ 评注: 1. velocity 的基本语法 2. 生成代码的用法.

随机推荐

  1. Dijkstra算法和Floyd算法的正确性证明

    说明: 本文仅提供关于两个算法的正确性的证明,不涉及对算法的过程描述和实现细节 本人算法菜鸟一枚,提供的证明仅是自己的思路,不保证正确,仅供参考,若有错误,欢迎拍砖指正   ------------- ...

  2. AcWing:175. 电路维修(bfs)

    达达是来自异世界的魔女,她在漫无目的地四处漂流的时候,遇到了善良的少女翰翰,从而被收留在地球上. 翰翰的家里有一辆飞行车. 有一天飞行车的电路板突然出现了故障,导致无法启动. 电路板的整体结构是一个R ...

  3. Marcin and Training Camp

    D. Marcin and Training Camp 参考:D. Marcin and Training Camp 思路:首先先确定最大成员的\(a_i\),因为不能够某个成员i认为自己比其他所有成 ...

  4. Codeforces 963 A. Alternating Sum(快速幂,逆元)

    Codeforces 963 A. Alternating Sum 题目大意:给出一组长度为n+1且元素为1或者-1的数组S(0~n),数组每k个元素为一周期,保证n+1可以被k整除.给a和b,求对1 ...

  5. MySQL_(Java)使用JDBC向数据库中插入(insert)数据

    MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC向数据库中插入(insert)数据 传送门 MySQL_(Java)使用JDBC向数据库中删除(d ...

  6. python3笔记十七:python文件读写

    一:学习内容 读文件 写文件 编码与解码 二:读文件--步骤分解 1.过程 第一步:打开文件第二步:读文件内容第三步:关闭文件 2.第一步:打开文件 open(path,flag[,encoding] ...

  7. hdu 1166 线段树 奇兵布阵

    #include<iostream> using namespace std; ; )*];//n个叶子就有2*n-4*n个节点 ]; int n; void getup(int root ...

  8. Location of Docker images in all Operating Systems (Linux, Windows, Redhat, Mac OS X)

    原文:http://www.scmgalaxy.com/tutorials/location-of-dockers-images-in-all-operating-systems/ Location ...

  9. CentOS7 开机启动脚本与命令后台运行

    一.& 在 Linux 命令后加上 &  可以在后台运行 二.nohup 对 SIGHUP 信号免疫,对 SIGINT 信号不免疫,可用 shopt | grep hup 查看. 当关 ...

  10. 哨兵模式java实例

    /** * 测试Redis哨兵模式 * @author liu */ public class TestSentinels { @SuppressWarnings("resource&quo ...