使用freemarker做郵件發送模板


1、解析工具類

package com.example.springbootfreemarker.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class FreeMarkerTemplateUtil {

    public String getEmailHtml(Map map, String templateName) {

        String htmlText = "";
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);
        try {
            //加載模板路徑
            configuration.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(),"ftl");
            //獲取對應名稱的模板
            Template template = configuration.getTemplate(templateName);
            //渲染模板為html
            htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return htmlText;
    }

    /**
     * 輸出到控制台
     */
    public void print(String name, Map<String, Object> root) throws TemplateException, IOException {
        //通過Template可以將模板文件輸出到相應的流
        Template template = this.getTemplate(name);
        template.process(root, new PrintWriter(System.out));
    }

    /**
     * 獲取模板信息
     *
     * @param name 模板名
     * @return
     */
    public Template getTemplate(String name) {
        //通過freemarkerd Configuration讀取相應的ftl
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
        //設定去哪里讀取相應的ftl模板文件,指定模板路徑
        cfg.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "ftl");
        try {
            //在模板文件目錄中找到名稱為name的文件
            Template template = cfg.getTemplate(name);
            return template;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

測試:

   //填充模板文件中的參數值
    Map<String, Object> root = null;
    FreeMarkerTemplateUtil freeMarkerTemplateUtil = null;

    @Before
    public void setUp(){
        freeMarkerTemplateUtil = new FreeMarkerTemplateUtil();
        root = new HashMap<String, Object>();
    }

    @Test
    public void testCreateHtml() throws Exception{

        root.put("username", "admin");

        String emailHtml = freeMarkerTemplateUtil.getEmailHtml(root, "reg.ftl");
//        System.out.println(">>>>" + emailHtml);

        root.put("username", "root");
        freeMarkerTemplateUtil.print("reg.ftl", root);

    }

 

源碼參照:使用freemarker做郵件發送模板


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM