JAVA发送邮件。

原创 2016年05月31日 14:20:39
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.setClassForTemplateLoading(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.setTemplateExceptionHandler(new FreemarkerFriendErrorHandler());
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;
}
}

内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:JAVA发送邮件。
举报原因:
原因补充:

(最多只允许输入30个字)