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>
郵件效果: