public class MailService {
private String mailFrom;
private Configuration cfg;
private JavaMailSenderImpl mailer;
public MailService(String mailFrom, String templPath, JavaMailSenderImpl mailer) {
this.mailFrom = mailFrom;
this.cfg = new Configuration();
this.cfg.setClassForTemplateLoadi
ng(this.getClass(), templPath);
this.cfg.setObjectWrapper(new DefaultObjectWrapper());
this.cfg.setDefaultEncoding("utf-8");
this.cfg.setEncoding(Locale.CHINA, "utf-8");
this.cfg.setStrictSyntaxMode("true".equals(System.getProperty(
"env.ftl.strict", "true")));
if (!"debug".equals(System.getProperty("env.ftl.error", "debug")))
this.cfg.setTemplateExceptionHand
ler(new FreemarkerFriendErrorHan
dler());
this.mailer = mailer;
}
public boolean sendHtmlMail(String to, String subject, String templ, Map vars) {
return sendHtmlMail(this.mailFrom, to, subject, templ, vars);
}
public boolean sendHtmlMail(String from, String to, String subject, String templ, Map vars) {
try {
Template freeMarker = this.cfg.getTemplate(templ);
Writer out = new StringWriter();
freeMarker.process(vars, out);
String messageBody = out.toString();
MimeMessage mail = mailer.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mail, false, "UTF-8");
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(messageBody, true);
mailer.send(mail);
} catch (IOException e) {
e.printStackTrace();
return false;
} catch(TemplateException e) {
e.printStackTrace();
return false;
} catch(MessagingException e) {
e.printStackTrace();
return false;
}
return true;
}
}