关闭

JAVA发送邮件。

313人阅读 评论(0) 收藏 举报
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;
}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:33365次
    • 积分:689
    • 等级:
    • 排名:千里之外
    • 原创:76篇
    • 转载:8篇
    • 译文:0篇
    • 评论:0条
    文章分类