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

转载 2012年03月21日 10:27:10

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>  


 

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

本文以用户注册后为用户发送一封邮件为例子,讲述如何在Spring中使用FreeMaker或Vilocity发送邮件。        Spring配置文件:             ...

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

本文以用户注册后为用户发送一封邮件为例子,讲述如何在Spring中使用FreeMaker或Vilocity发送邮件。        Spring配置文件:               ...

spring使用模板发送邮件及附件笔记

需要引用的jar包: mail-1.4.1.jar activation-1.1.jar spring-context-support-2.5.jar spring-webmvc.jar ...

Spring 4 使用Freemarker模板发送邮件&添加附件

 阅读目录 前言Bean配置——JavaMailSenderImplBean配置——FreeMarkerConfigurationFactoryBean编写邮件发送ServiceCon...

spring使用模板发送邮件及附件笔记

需要引用的jar包: mail-1.4.1.jar activation-1.1.jar spring-context-support-2.5.jar spring-webmvc.jar ...

spring使用模板发送邮件及附件笔记

需要引用的jar包: mail-1.4.1.jar activation-1.1.jar spring-context-support-2.5.jar spring-webmv...

Velocity 、Freemarker模板及Spring Api实现发送邮件

Veloctiy1、spring配置文件
  • dalinsi
  • dalinsi
  • 2017年07月11日 19:32
  • 390

java 利用spring JavaMailSenderImpl发送邮件,支持普通文本、附件、html、velocity模板

本文主要介绍利用JavaMailSenderImpl发送邮件。首先介绍了发送一般邮件,然后介绍了发送富文本(html)邮件及以velocity为模板发送邮件。   邮件发送分为为三步:创建...

怎么使用Spring发送邮件

原来来自:http://sunny.blog.51cto.com/182601/32623 关于Spring的邮件发送的功能演示: (我把程序中一些敏感的地方替换成了其他的文字,直接调...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Spring中使用FreeMaker或Vilocity模板发送邮件
举报原因:
原因补充:

(最多只允许输入30个字)