利用 spring+freemarker 发送邮件

最近公司要用到给注册会员发送邮件的功能,这里采用spring+freemarker模板来发送邮件,其中模板可以自定义,欲了解freemarker请看我写的利用freemarker 静态化网页,里面介绍的很详细和怎么使用。

在做本次试验之前需要spring相关的jar和freemarker.jar

①定义发送邮件的模板

demo.ftl

<!--这里可以写html代码,传递过来的参数可以用${}来接收 ,很是方便-->

<a href="http://www.xxx.com">你好${username}</a>

②发送邮件java类

package com.woaika.loan.utils;

import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;

/**
 * 发送邮件 可以自己编写html模板
 * @author ajun
 * @email zhaojun2066@gmail.com
 * @blog http://blog.csdn.net/ajun_studio
 * 2011-12-6 下午04:49:01
 */
public class TemplateEmail {

	private JavaMailSender sender;  
    private FreeMarkerConfigurer freeMarkerConfigurer=null;//FreeMarker的技术类  
      
    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {  
        this.freeMarkerConfigurer = freeMarkerConfigurer;  
    }  
      
    public void setSender(JavaMailSender sender) {  
        this.sender = sender;  
    }  
    
    /**
     * 生成html模板字符串
     * @param root 存储动态数据的map
     * @return
     */
	private String getMailText(Map<String,Object> root,String templateName){
		 String htmlText="";  
	        try {  
	            //通过指定模板名获取FreeMarker模板实例  
	            Template tpl=freeMarkerConfigurer.getConfiguration().getTemplate(templateName);  
	            htmlText=FreeMarkerTemplateUtils.processTemplateIntoString(tpl,root);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        return htmlText;  
	}
	
	/**
	 * 发送邮件
	 * @param root 存储动态数据的map
	 * @param toEmail 邮件地址
	 * @param subject 邮件主题
	 * @return
	 */
    public boolean sendTemplateMail(Map<String,Object> root,String toEmail,String subject,String templateName){  
        try {
			MimeMessage msg=sender.createMimeMessage();  
			MimeMessageHelper helper=new MimeMessageHelper(msg,false,"utf-8");//由于是html邮件,不是mulitpart类型  
			helper.setFrom("admin@xxx.com");  
			helper.setTo(toEmail);  
			helper.setSubject(subject);  
			String htmlText=getMailText(root,templateName);//使用模板生成html邮件内容  
			helper.setText(htmlText, true);  
			sender.send(msg);
			//System.out.println("成功发送模板邮件");  
			return true;
		} catch (MailException e) {
		   // System.out.println("失败发送模板邮件"); 
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
		//	System.out.println("失败发送模板邮件"); 
			e.printStackTrace();
			return false;
		}  
       
    }  
}


③实例化相关freemarker类的配置文件,并交给spring来管理

applicationContext-sendMail.xml


<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
           
	<bean id="freeMarker" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
	  <property name="templateLoaderPath" value="classpath:mailtemplates"/><!--指定模板文件目录--> 
	  <property name="freemarkerSettings"><!-- 设置FreeMarker环境属性--> 
	      <props>
	          <prop key="template_update_delay">1800</prop><!--刷新模板的周期,单位为秒--> 
	          <prop key="default_encoding">UTF-8</prop><!--模板的编码格式 -->
	          <prop key="locale">zh_CN</prop><!-- 本地化设置-->
	      </props>
	  </property>
	</bean>
	<bean id="templateEmail" class="com.woaika.loan.utils.TemplateEmail">
	    <property name="sender" ref="mailsender"></property>
	    <property name="freeMarkerConfigurer" ref="freeMarker"></property>
	</bean> 
	
	<bean id="mailsender"  
        class="org.springframework.mail.javamail.JavaMailSenderImpl">  
        <property name="host">  
            <value>mail.xx.com</value>  
        </property>  
        <property name="javaMailProperties">  
            <props>  
                <prop key="mail.smtp.auth">true</prop>  
                <prop key="mail.smtp.timeout">25000</prop>  
            </props>  
        </property>  
        <property name="username">  
            <value>admin</value>  
        </property>  
        <property name="password">  
            <value>qq22qq56we</value>  
        </property>  
    </bean>  
	
</beans>

④调用的时候,只需调用的类中注入TemplateEmail这个,然后调用相关的方法就可以了


package com.woaika.loan.front.apply.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.woaika.loan.utils.TemplateEmail;

/**
 * 发送邮件
 * @author ajun
 * @email zhaojun2066@gmail.com
 * @blog http://blog.csdn.net/ajun_studio
 * 2012-3-13 上午10:50:26
 */
@Component("demoEmail")
public class DemoEmail {

	private TemplateEmail templateEmail;
	
	@Resource(name="templateEmail")
	public void setTemplateEmail(TemplateEmail templateEmail) {
		this.templateEmail = templateEmail;
	} 
	
	public void send(){
		Map<String,Object> root = new HashMap<String,Object>();
		root.put("username", "ajun");
		templateEmail.sendTemplateMail(root, "ajun@gmail.com","主题标题","demo.ftl");
	}
	
	
	
}

ok ,赶快试试吧 很方便,而且spring可以定时帅新模板,这样就可以不重启服务了



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飓风zj

感谢打赏,thanks

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值