转载文章并说明自己遇到的问题,感谢两文作者:
参考: https://www.cnblogs.com/chancy/p/10456210.html
并结合:https://www.jianshu.com/p/207f193496a6 (引入freemarker依赖,读取模板)
项目中遇到的问题:
我的springboot 引入的是jsp页面 ,如果使用template的TemplateEngine模板引擎去获取模板文件,这就需要引入spring-boot-starter-thymeleaf 依赖。如果我引入thymeleaf 依赖,会导致页面解析失败,jsp页面无法访问;可能就需要同时配置支持html+jsp 视图解析,未继续
后来我是按照参考了另一篇文章,引入freemarker依赖,去获取模板文件,就不会出现页面解析失败。
//读取邮件模板文件,两种方式: //方式一: 使用template模板引擎,这种方式需要引入 template依赖,但因为项目使用的jsp页面,引入此依赖会导致无法访问jsp页面404; //因此项目需要配置视图解析器,同时支持jsp+html ,此方式省略 // @Autowired // private TemplateEngine templateEngine; // //Context是导这个包import org.thymeleaf.context.Context; // Context context = new Context(); // //定义模板数据 // context.setVariables(email.getAttachment()); // //获取thymeleaf的html模板 // String emailContent = templateEngine.process("/mail/elc_invoice",context); //指定模板路径 // helper.setText(emailContent,true); //邮件内容 //方式二:引入spring-boot-starter-freemarker依赖,通过其获取模板文件 Configuration cfg=new Configuration(Configuration.VERSION_2_3_23); //设置去哪里读取响应的模板 cfg.setClassForTemplateLoading(this.getClass(),"/templates/mail"); //在模板中文件目录中寻找名称为name的模板文件 Template template=cfg.getTemplate("elc_invoice.ftl"); String html= FreeMarkerTemplateUtils.processTemplateIntoString(template,email.getAttachment()); helper.setText(html,true); //邮件内容