1、引入依赖
<!-- 引入freeMarker的依赖包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、创建模板文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送邮件测试</title>
</head>
<body>
<p>内容:${content}</p>
<p>日期:${time?date}</p>
</body>
</html>
注意,这里的${time?date}表示time是日期类型的变量,只取date部分。“?date”还可以使用“?datetime”或“?time”。
3、使用模板引擎
@Autowired
FreeMarkerConfigurer configurer;//模板引擎
@Test
public String index(Map map) throws IOException, TemplateException {
map.put("content","哈哈哈");
map.put("time",new Date());
Template template = configurer.getConfiguration().getTemplate("mail.ftl");
String resp = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
return resp;
}
附:使用循环遍历一个List的模板:(转)
<html>
<body>
<h3>发现错误!<a href="${errorLogLink}" target="_blank">点击这里查看详情</a></h3>
<h3>错误列表:</h3>
<table border="1px solid #8968CD" style="border-collapse: collapse;"><tr><th>错误位置</th> <th>数量</th> <th>错误信息</th> <th>错误类名</th> <th>更多信息</th> </tr>
<#list errorList as error>
<tr>
<td>${error.pos}</td>
<td>${error.count}</td>
<td>${error.msg}</td>
<td>${error.eName!}</td>
<td>${error.details!}</td>
</tr>
</#list>
</table>
</body>
</html>
注意:最后那个两个感叹号表示:如果error.eName/error.details的值为空,则用空格代替。感叹号后面也可以加一个缺省字符串,在空值的时候代替空值。如果不加感叹号会报错。