SpringBoot 整合FreeMarker进行邮件发送
SpringBoot 整合FreeMarker进行邮件发送
在发送使用程序发送邮件时,如果邮件的内容过多,全部在代码里进行内容的拼接,会造成代码块很大,增大代码量,而且每次修改邮件模板的时候都要在代码里面进行修改,不是很便利;
因此才有了使用FreeMarker这个模板引擎来制作邮件模板,然后动态的填充变化的内容进去即可生成完整的邮件内容;下面是Springboot + freemarker来实现邮件模板动态生成邮件内容的演示;
预备知识:
什么是FreeMarker,可以参考官网http://freemarker.foofun.cn/index.html ;
因为我们这里只使用了它最基本的动态替换的功能,你可以简单理解为它像thymeleaf,JSP一样,就是一个模板引擎,基于模板动态生成最终文本数据即可。
1. 引入依赖
<!--引入freemarker--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> <version>2.3.5.RELEASE</version> </dependency>
2. 配置freemarker
spring:
profiles:
active: dev
# freemarker默认存放路径
freemarker:
template-loader-path: classpath:/templates/freemarker/
3. 准备一个文件模板
文件名以 .ftl 为后缀,例如 helloworld.ftl;mailtest.ftl
<!DOCTYPE html> <html> <body> <h4>${UserName},你好!</h4> <#list pets as pet> <p>${pet} </#list> </body> </html>
<!DOCTYPE html> <html> <head><meta http-equiv=Content-Type content="text/html; charset=utf-8"/></head> <div style=font-family: Arial>Dear Mr./Ms. ${username},</br> 以下为最近7天内即将到期关闭的任务,请及时关注,谢谢 </div><br> <#list rows> <table style=font-size:12px border=1 cellspacing=0 width=100% bordercolorlight=DarkGray bordercolordark=#efefef> <tr><th>代码</th><th>任务名称</th><th>到期日期</th><th>剩余天数</th></tr> <#items as row> <tr> <td>${row.id}</td> <td>${row.name}</td> <td>${row.expirydate}</td> <td>${row.surplus}</td> </tr> </#items> </table> </#list> <br> <div align="right" style="font-size: 11pt;line-height:2em;" > <strong>IT</strong><br/> If you have any IT related questions, please send your request to <a href='http://www.baidu.com'>Baidu.</a><br/> <script> var day=new Date();document.write (day.toString());</script> </div> </html>
4. 写个测试类验证
关键代码就两三行,代码里没有杂乱的字符串拼接,看起来会简洁很多。
1 import freemarker.template.Configuration; 2 import freemarker.template.Template; 3 import org.junit.jupiter.api.DisplayName; 4 import org.junit.jupiter.api.Test; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.boot.test.context.SpringBootTest; 7 import org.springframework.mail.javamail.JavaMailSender; 8 import org.springframework.mail.javamail.MimeMessageHelper; 9 import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; 10 11 import javax.mail.internet.MimeMessage; 12 import java.util.*; 13 14 15 /** 16 * @author: Linwei 17 * @date 2021/4/7 18 * @Description: 19 */ 20 21 @SpringBootTest 22 public class FreeMarkerTest { 23 24 // 自动注入FreeMarker配置类,用户获取模板 25 @Autowired 26 private Configuration configuration; 27 28 // 注入Spring发送邮件的工具类 29 @Autowired 30 private JavaMailSender sender; 31 32 33 @Test 34 @DisplayName("测试freemarker") 35 public void test() throws Exception{ 36 // 定义个数据根节点 37 Map<String,Object> root = new HashMap<>(); 38 // 往里面塞第一层节点 39 root.put("UserName","xiaoming"); 40 41 String[] temp = new String[]{"dog","cat","tiger"}; 42 List<String> pets = new ArrayList<>(); 43 Collections.addAll(pets,temp); 44 // 往里面塞个List对象 45 root.put("pets", pets); 46 47 Template template = configuration.getTemplate("helloworld.ftl"); 48 String s = FreeMarkerTemplateUtils.processTemplateIntoString(template, root); 49 System.out.println("--->"+s); 50 51 MimeMessage mimeMessage = sender.createMimeMessage(); 52 /** 设置邮件重要性级别 */ 53 mimeMessage.setHeader("Importance","High"); 54 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); 55 helper.setFrom("Intranet.FM@test.com","personalTest"); 56 helper.setTo("Zhangsan@test.com"); 57 helper.setSubject("This is subject 主题"); 58 helper.setText(s,true); 59 sender.send(mimeMessage); 60 } 61 62 @Test 63 @DisplayName("测试邮件模板") 64 public void testMailFreeMark() throws Exception{ 65 List<Map<String, String>> rows = new ArrayList<>(); 66 Map<String, String> map = new HashMap<>(); 67 map.put("id","314016163491"); 68 map.put("name","小白"); 69 map.put("expirydate","2021-04-21"); 70 map.put("surplus","61"); 71 Map<String, String> map2 = new HashMap<>(); 72 map2.put("id","31400000024"); 73 map2.put("name","小黑"); 74 map2.put("expirydate","2021-04-22"); 75 map2.put("surplus","2"); 76 rows.add(map);rows.add(map2); 77 // 定义个数据根节点 78 Map<String,Object> root = new HashMap<>(); 79 root.put("username","zhangsan"); 80 root.put("rows",rows); 81 Template template = configuration.getTemplate("mailtest.ftl"); 82 String s = FreeMarkerTemplateUtils.processTemplateIntoString(template, root); 83 System.out.println("--->"+s); 84 } 85 86 }
文本效果:
<!DOCTYPE html> <html> <head><meta http-equiv=Content-Type content="text/html; charset=utf-8"/></head> <div style=font-family: Arial>Dear Mr./Ms. zhangsan,</br> 以下为最近7天内即将到期关闭的任务,请及时关注,谢谢 </div><br> <table style=font-size:12px border=1 cellspacing=0 width=100% bordercolorlight=DarkGray bordercolordark=#efefef> <tr><th>代码</th><th>任务名称</th><th>到期日期</th><th>剩余天数</th></tr> <tr> <td>314016163491</td> <td>小白</td> <td>2021-04-21</td> <td>61</td> </tr> <tr> <td>31400000024</td> <td>小黑</td> <td>2021-04-22</td> <td>2</td> </tr> </table> <br> <div align="right" style="font-size: 11pt;line-height:2em;" > <strong>IT</strong><br/> If you have any IT related questions, please send your request to <a href='http://www.baidu.com'>Baidu.</a><br/> <script> var day=new Date();document.write (day.toString());</script> </div> </html>
邮件效果:
边系鞋带边思考人生.