jmail +freemaker send html format mail

background:

A few days ago, a PM set up an email service and asked me to integrate sending emails into the system. I have used jmail to send before. Since it is a product made this time, the UI requirements are very high. So request mail to send html. Splicing from java is really confusing and not easy to modify. So I thought of using the template to get it

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);
}

} -->

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325462685&siteId=291194637