jmail +freemaker 发送html格式邮件

背景:

前几天有个pm搭建了个邮件服务,让我把发送邮件整合到系统里面。以前用过jmail发送过。由于这次是做的产品,所以对ui要求很高。所以要求邮件发送html。从java里面拼接实在是混乱,也不易修改。所以想到了利用模板来搞定

jar :jmail 1.4+ struts2+freemaker

java:

<!-- public String forgetPwd() {
    HttpServletRequest request = ServletActionContext.getRequest();
    String email = request.getParameter("email");
    Map<String, String> map = new HashMap<String, String>();
    try {
                    //templates  里面需要的传人的值
        Map<String, String> sendMap = new HashMap<String, String>();
                    //加载templates 正式环境可以采用预加载方式
        String path = "E:\\myEclipse8.6\\fileboxServer\\defaultroot\\WEB-INF\\templates";
        sendMap.put("now", DataUtils.date2String(DataUtils.getNow()));
        sendMap.put("email", email);
        sendMap.put("href",
                "http://localhost:8080/html/account/reset_password.html?email="
                        + email);
        Jmail.sendMail(email, "找回密码", path, "finfPwd.ftl", sendMap);
    } catch (Exception e) {
        this.error = err(map);
        e.printStackTrace();
        return error;
    }
    this.result = success(map);
    return SUCCESS;
}  -->

jmail :

<!-- 
/**
 * 使用Freemarker生成html格式内容.
 */
public static String generateContent(Map<String, String> map, String path,
        String ftl) throws MessagingException {
    try {
        try {
            Configuration freemarkerConfiguration = new Configuration();
            // 可以再初始化selvelt时加载
            File f = new File(path);
            freemarkerConfiguration.setDirectoryForTemplateLoading(f);
            Template template = freemarkerConfiguration.getTemplate(ftl,
                    "utf-8");
            return FreeMarkerTemplateUtils.processTemplateIntoString(
                    template, map);
        } catch (IOException e) {
            throw new MessagingException("FreeMarker模板不存在", e);
        }
    } catch (TemplateException e) {
        throw new MessagingException("FreeMarker处理失败", e);
    }

}

public static void main(String args[]) {
    try {
        String email="[email protected]";
        Map<String, String> sendMap = new HashMap<String, String>();
        String path = "E:\\myEclipse8.6\\fileboxServer\\defaultroot\\WEB-INF\\templates";
        sendMap.put("now", DataUtils.date2String(DataUtils.getNow()));
        sendMap.put("email", email);
        sendMap.put("href",
                "http://localhost:8080/html/account/reset_password.html?email="
                        + email);
        Jmail.sendMail(email, "找回密码", path, "finfPwd.ftl", sendMap);
            } catch (MessagingException e) {
        e.printStackTrace();
    }
}

/**
 * @param email
 *            发送到的email
 * @param subject
 *            主题
 * @param path
 *            模板所在的路径
 * @param path
 *            加载的模板
 * @param path
 *            模板要加载的参数
 * @throws MessagingException
 */
@SuppressWarnings("static-access")
public static void sendMail(String email, String subject, String path,
        String template, Map<String, String> map) throws MessagingException {

    // 第一步:配置javax.mail.Session对象
    System.out.println("为smtp.filebox.com.cn 配置mail session对象");

    Properties props = new Properties();
    props.put("mail.smtp.host", EMAIL_PORT);
    props.put("mail.smtp.starttls.enable", "true");// 使用 STARTTLS安全连接
    // props.put("mail.smtp.port", "25"); //google使用465或587端口
    props.put("mail.smtp.auth", "true"); // 使用验证
    // props.put("mail.debug", "true");
    Session mailSession = Session.getInstance(props,new MyAuthenticator(EMAIL_USRTID,EMAIL_PWD) );

// Session mailSession = Session.getInstance(props);

    // 第二步:编写消息

    InternetAddress fromAddress = new InternetAddress(EMAIL_FROM);
    InternetAddress toAddress = new InternetAddress(email);

    MimeMessage message = new MimeMessage(mailSession);

    message.setFrom(fromAddress);
    message.addRecipient(RecipientType.TO, toAddress);

    message.setSentDate(Calendar.getInstance().getTime());
    message.setSubject(subject);
    message.setContent(Jmail.generateContent(map, path, template),
            EMAIL_TYPE);
    // 第三步:发送消息
    Transport transport = mailSession.getTransport("smtp");
    //transport.connect("service","service123");
    transport.connect();
    transport.send(message, message.getRecipients(RecipientType.TO));
    System.out.println("message yes");
}

}

class MyAuthenticator extends Authenticator {

String userName = "";
String password = "";

public MyAuthenticator() {

}

public MyAuthenticator(String userName, String password) {
    this.userName = userName;
    this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(userName, password);
}

}
–>

你可能感兴趣的:(jmail +freemaker 发送html格式邮件)