Spring中使用FreeMaker或Vilocity发送邮件(转)
??????? 本文以用户注册后为用户发送一封邮件为例子,讲述如何在Spring中使用FreeMaker或Vilocity发送邮件。
?????? Spring配置文件:
<!-- 使用Spring封装的Mail Sender -->
??? <bean id="mailSender" value="smtp.163.com"/>
??????? <property name="username" value="test"/>
??????? <property name="password" value="123456"/>
??????? <property name="javaMailProperties">
????????????? <props>
??????????????? <prop key="mail.smtp.auth">true</prop>
????????????? </props>
??????? </property>
??? </bean>
??? <!-- freemarker config -->
??? <bean id="freeMarkerConfigurer"??????????????????? value="/WEB-INF/freemakertemplate/" />
??????? <property name="freemarkerSettings">
??????????? <props>
??????????????? <prop key="template_update_delay">0</prop>
??????????????? <prop key="default_encoding">GBK</prop>
??????????????? <prop key="locale">zh_CN</prop>
??????????? </props>
??????? </property>
??? </bean>
???
??? <!-- vilocity config -->
??? <bean id="velocityEngine" value="/WEB-INF/vilocitytemplate/" />
??????? <property name="velocityProperties">
??????????? <props>
??????????????? <prop key="velocimacro.library">*.vm</prop>
??????????????? <prop key="default.contentType">text/html; charset=utf-8</prop>
??????????????? <prop key="output.encoding">utf-8</prop>
??????????????? <prop key="input.encoding">utf-8</prop>
??????????? </props>
??????? </property>
??? </bean>
???
???? <bean id="mailMessage" singleton="false">
??????? <property name="from" value="test@163.com"/>
??? </bean>
???
??? <bean id="mailEngine" ref="mailSender"/>
??????? <!-- 如果使用Vilocity -->
??????? <property name="velocityEngine" ref="velocityEngine"/>
?????? <!-- 如果使用FreeMaker -->
?????? <property name="freeMarkerConfigurer" ref="freeMarkerConfigurer" />
??? </bean>
???
?
??? MailEngine类:
public class MailEngine {
??? protected static final Log log = LogFactory.getLog(MailEngine.class);
//??? private FreeMarkerConfigurer freeMarkerConfigurer;
??? private VelocityEngine velocityEngine;
??? private MailSender mailSender;
//??? public void setFreeMarkerConfigurer(
//??????????? FreeMarkerConfigurer freeMarkerConfigurer) {
//??????? this.freeMarkerConfigurer = freeMarkerConfigurer;
//??? }
??? public void setMailSender(MailSender mailSender) {
??????? this.mailSender = mailSender;
??? }
??? public void setVelocityEngine(VelocityEngine velocityEngine) {
??????? this.velocityEngine = velocityEngine;
??? }
??? /**
???? * 通过模板产生邮件正文
???? * @param templateName??? 邮件模板名称
???? * @param map??????????? 模板中要填充的对象
???? * @return 邮件正文(HTML)
???? */
??? public String generateEmailContent(String templateName, Map map) {
??????? //使用FreeMaker模板
//??????? try {
//??????????? Configuration configuration = freeMarkerConfigurer.getConfiguration();
//??????????? Template t = configuration.getTemplate(templateName);
//??????????? return FreeMarkerTemplateUtils.processTemplateIntoString(t, map);
//??????? } catch (TemplateException e) {
//??????????? log.error("Error while processing FreeMarker template ", e);
//??????? } catch (FileNotFoundException e) {
//??????????? e.printStackTrace();
//??????????? //log.error("Error while open template file ", e);
//??????? } catch (IOException e) {
//??????????? log.error("Error while generate Email Content ", e);
//??????? }
???????
//??????? 使用Vilocity模板
??????? try {
?????????? return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, map);
??????? } catch (VelocityException e) {
??????????? log.error("Error while processing Vilocity template ", e);
??????? }
???????
??????? return null;
??? }
??? /**
???? * 发送邮件
???? * @param emailAddress??????? 收件人Email地址的数组
???? * @param fromEmail??????????? 寄件人Email地址, null为默认寄件人web@vnvtrip.com
???? * @param bodyText??????????? 邮件正文
???? * @param subject??????????? 邮件主题
???? * @param attachmentName??? 附件名
???? * @param resource??????????? 附件
???? * @throws MessagingException
???? */
??? public void sendMessage(String[] emailAddresses, String fromEmail,
??????????? String bodyText, String subject, String attachmentName,
??????????? ClassPathResource resource) throws MessagingException {
??????? MimeMessage message = ((JavaMailSenderImpl) mailSender)
??????????????? .createMimeMessage();
??????? // use the true flag to indicate you need a multipart message
??????? MimeMessageHelper helper = new MimeMessageHelper(message, true);
??????? helper.setTo(emailAddresses);
??????? if(fromEmail != null){
??????????? helper.setFrom(fromEmail);
??????? }
??????? helper.setText(bodyText, true);
??????? helper.setSubject(subject);
???????
??????? if(attachmentName!=null && resource!=null)
??????????? helper.addAttachment(attachmentName, resource);
??????? ((JavaMailSenderImpl) mailSender).send(message);
??? }
??? /**
???? * 发送简单邮件
???? * @param msg???
???? */
??? public void send(SimpleMailMessage msg) {
??????? try {
??????????? ((JavaMailSenderImpl) mailSender).send(msg);
??????? } catch (MailException ex) {
??????????? //log it and go on
??????????? log.error(ex.getMessage());
??????? }
??? }
???
??? /**
???? * 使用模版发送HTML格式的邮件
???? *
???? * @param msg????????? 装有to,from,subject信息的SimpleMailMessage
???? * @param templateName 模版名,模版根路径已在配置文件定义于freemakarengine中
???? * @param model??????? 渲染模版所需的数据
???? */
??? public void send(SimpleMailMessage msg, String templateName, Map model) {
??????? //生成html邮件内容
??????? String content = generateEmailContent(templateName, model);
??????? MimeMessage mimeMsg = null;
??????? try {
??????????? mimeMsg = ((JavaMailSenderImpl) mailSender).createMimeMessage();
??????????? MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true, "utf-8");
??????????? helper.setTo(msg.getTo());
???????????
??????????? if(msg.getSubject()!=null)
??????????????? helper.setSubject(msg.getSubject());
???????????
??????????? if(msg.getFrom()!=null)
??????????????? helper.setFrom(msg.getFrom());
???????????
??????????? helper.setText(content, true);
???????????
??????????? ((JavaMailSenderImpl) mailSender).send(mimeMsg);
??????? } catch (MessagingException ex) {
??????????? log.error(ex.getMessage(), ex);
??????? }
??? }
}
发送邮件:
SimpleMailMessage message = (SimpleMailMessage) getBean("mailMessage");
??????????????? message.setTo(user.getName() + "<" + user.getEmail() + ">");
???????????????
??????????????? Map<String, User> model = new HashMap<String, User>();
??????????????? model.put("user", user);
???????????????
??????????????? MailEngine engine = (MailEngine)getBean("mailEngine");
??????????????? //Vilocity模板
??????????????? engine.send(message, "notifyUser.vm", model);
??????????????? //FreeMaker模板
??????????????? //engine.send(message, "NotifyUser.ftl", model);
以上的User为用户类。
Vilocity模板:
${user.name} 您好!您已成功注册为本站会员,您的信息如下:
${user.name}
${user.password}
FreeMaker模板:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>用户注册通知</title>
</head>
<body>
<p>${user.name} 您好,恭喜您,已经成为本站会员!</p>
<table>
<tr><td>用户名:</td><td>${user.name}</td></tr>
<tr><td>密码:</td><td>${user.password}</td></tr>
</table>
</body>
</html>