jmail +freemaker 發送html格式郵件

背景:html

前幾天有個pm搭建了個郵件服務,讓我把發送郵件整合到系統裏面。之前用過jmail發送過。因爲此次是作的產品,因此對ui要求很高。因此要求郵件發送html。從java裏面拼接實在是混亂,也不易修改。因此想到了利用模板來搞定java

jar :jmail 1.4+ struts2+freemaker安全

java:session

<!-- 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 :ui

<!-- 
/**
 * 使用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="test@163.com";
		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);this

// 第二步:編寫消息

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

}google

class MyAuthenticator extends Authenticator { String userName = ""; String password = "";debug

public MyAuthenticator() {

}

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

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

} -->code

相關文章
相關標籤/搜索