Spring整合freemarker发送邮件mail, 附件
http://blog.csdn.net/zdp072/article/details/32745335
发送实现类,详细看原文
public class EmailServiceImpl implements EmailService { private JavaMailSender mailSender; private FreeMarkerConfigurer freeMarkerConfigurer; private static final String ENCODING = "utf-8"; public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; } public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) { this.freeMarkerConfigurer = freeMarkerConfigurer; } /** * 发送带附件的html格式邮件 */ public void sendEmail(User user) { MimeMessage msg = null; try { msg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, true, ENCODING); helper.setFrom("[email protected]"); helper.setTo("[email protected]"); helper.setSubject(MimeUtility.encodeText("estore注册成功提示邮件", ENCODING, "B")); helper.setText(getMailText(user), true); // true表示text的内容为html // 添加内嵌文件,第1个参数为cid标识这个文件,第2个参数为资源 helper.addInline("welcomePic", new File("d:/welcome.gif")); // 附件内容 // 这里的方法调用和插入图片是不同的,解决附件名称的中文问题 File file = new File("d:/欢迎注册.docx"); helper.addAttachment(MimeUtility.encodeWord(file.getName()), file); } catch (Exception e) { throw new RuntimeException("error happens", e); } mailSender.send(msg); System.out.println("邮件发送成功..."); } /** * 通过模板构造邮件内容,参数content将替换模板文件中的${content}标签。 */ private String getMailText(User user) throws Exception { // 通过指定模板名获取FreeMarker模板实例 Template template = freeMarkerConfigurer.getConfiguration().getTemplate("registe.html"); // FreeMarker通过Map传递动态数据 Map<String, String> map = new HashMap<String, String>(); map.put("username", user.getUsername()); // 注意动态数据的key和模板标签中指定的属性相匹配 map.put("password", user.getPassword()); // 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。 String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); return htmlText; } }
相关推荐
81314797 2020-11-18
89314493 2020-11-03
81941231 2020-09-17
thisisid 2020-09-09
如狼 2020-08-15
82384399 2020-06-16
86384798 2020-05-12
80183053 2020-05-02
86384798 2020-04-26
86384798 2020-04-11
rionchen 2020-04-09
86384798 2020-04-07
86384798 2020-04-04
80183053 2020-03-07
87201943 2020-03-06
83961233 2020-02-26
87201943 2020-02-21