关闭

Spring中使用FreeMaker或Vilocity模板发送邮件

626人阅读 评论(0) 收藏 举报

Spring配置文件:

 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">   
         <property name="host" 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>   
 <bean id="freeMarkerConfigurer"  class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">   
        <property name="templateLoaderPath" 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>          
  <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">   
        <property name="resourceLoaderPath" 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" class="org.springframework.mail.SimpleMailMessage" singleton="false">   
       <property name="from" value="test@163.com"/>   
  </bean>          
  <bean id="mailEngine" class="test.MailEngine">   
         <property name="mailSender" ref="mailSender"/>   
         <property name="velocityEngine" ref="velocityEngine"/>   
         <property name="freeMarkerConfigurer" ref="freeMarkerConfigurer" />   
  </bean>   

 MailEngine类:

package common;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

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)
     */
    // 使用FreeMaker模板
    public String generateEmailContentByFreeMarker(String templateName,
	    Map<?, ?> map) {
	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);
	}
	return null;
    }

    // 使用Vilocity模板
    public String generateEmailContent(String templateName, Map<?, ?> map) {

	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 = null;
	try {
	    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);
	} catch (javax.mail.MessagingException e) {
	    e.printStackTrace();
	}
	((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 (javax.mail.MessagingException e) {
	    e.printStackTrace();
	}

    }
}

 

SimpleMailMessage message = (SimpleMailMessage) getBean("mailMessage");    
message.setTo(user.getName() + "<" + user.getEmail() + ">");    
Map model = new HashMap();    
model.put("user", user);                       
MailEngine engine = (MailEngine)getBean("mailEngine");    
//Vilocity模板    
engine.send(message, "notifyUser.vm", model);    
//FreeMaker模板    
//engine.send(message, "NotifyUser.ftl", model);    
以上的User为用户类。   

模板:

  
<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>  


 

0
0

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