spring- boot 傳送郵件介面+freemarker檢視模板引擎
阿新 • • 發佈:2019-01-22
1.建立模板引擎服務:
package com.ftvalue.customer.service;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import java.io.IOException;
import java.util.Map;
/**
* Created by 郝丹輝 on 2017/9/19.
*/
public class TempleEngineService {
public static String EmailTemplate(String templateName,Map model) throws IOException, TemplateException {
Configuration configuration = new Configuration();
TemplateLoader c1 = new ClassTemplateLoader(TemplateLoader.class,"/static/templates");
configuration.setTemplateLoader(c1);
Template template = configuration.getTemplate(templateName);
String txt = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);
return txt;
}
}
2.在介面方法中呼叫:
@Override
public String sendEmail(String mailTemplate,String mailTitle,String target,Map model) {
String response = null;
try{
//引用模板引擎
String txt = TempleEngineService.EmailTemplate(mailTemplate,model);
Map<String,String> args = new HashMap<>();
args.put("to",target);
args.put("subject",URLEncoder.encode(mailTitle,"GBK"));
args.put("charset","GBK");
args.put("body",URLEncoder.encode(txt,"GBK"));
log.info("args:"+args);
response = HttpUtil.getResponseBody(args,ymlConfig.getIsmpEimsEmail());
}catch (Exception e){
log.error("郵件服務異常:"+e.getMessage());
try {
throw new Exception("郵件服務異常");
} catch (Exception e1) {
e1.printStackTrace();
}
}
return response;
}