spring,freemarker,异步发邮件

1.引入jar.

 

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.1.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.1.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.1.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.20</version>
</dependency>
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4</version>
</dependency>


2.mailtemplates模板目录下制作demo.ftl模板

 

 

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

3.spring配置文件

 

 

<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="templateEmail" class="com.xxx.xxx.base.TemplateEmail">
        <property name="sender" ref="mailsender"></property>
        <property name="threadPool" ref="threadPool"></property>
        <property name="freeMarkerConfigurer" ref="freeMarker"></property>
    </bean>

    <bean id="mailsender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host">
            <value>mail.xxx.com</value>
        </property>
        <property name="username">
            <value>aaa</value>
        </property>
        <property name="password">
            <value>bbb</value>
        </property>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.timeout">25000</prop>
            </props>
        </property>
    </bean>

    <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="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <!-- 核心线程数  -->
        <property name="corePoolSize" value="4" />
        <!-- 最大线程数 -->
        <property name="maxPoolSize" value="30" />
        <!-- 队列最大长度 >=mainExecutor.maxSize -->
        <property name="queueCapacity" value="50" />
        <!-- 线程池维护线程所允许的空闲时间 -->
        <property name="keepAliveSeconds" value="300" />
        <!-- 线程池对拒绝任务(无线程可用)的处理策略 -->
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
        </property>
    </bean>
</beans>


4.发送类

 

 

import freemarker.template.Template;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 发送邮件 可以自己编写html模板
 * Created by aaa on 2017/5/12.
 */
public class TemplateEmail {

    private JavaMailSender sender;
    private ThreadPoolTaskExecutor threadPool;
    private FreeMarkerConfigurer freeMarkerConfigurer=null;//FreeMarker的技术类
    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
        this.freeMarkerConfigurer = freeMarkerConfigurer;
    }
    public void setSender(JavaMailSender sender) {
        this.sender = sender;
    }

    public void setThreadPool(ThreadPoolTaskExecutor threadPool) {
        this.threadPool = threadPool;
    }

    /**
     * 生成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 void sendTemplateMail(final Map<String,Object> root,final  String toEmail,final String subject,final String templateName){
        //异步发送邮件
        threadPool.execute(new Runnable() {
            public void run() {
                try {
                    MimeMessage msg=sender.createMimeMessage();
                    MimeMessageHelper helper=new MimeMessageHelper(msg,false,"utf-8");//由于是html邮件,不是mulitpart类型
                    helper.setFrom("b2b_service@xxx.com");
                    helper.setTo(toEmail);
                    helper.setSubject(subject);
                    String htmlText=getMailText(root,templateName);//使用模板生成html邮件内容
                    helper.setText(htmlText, true);
                    sender.send(msg);
                } catch (MailException e) {
                    e.printStackTrace();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}


5.测试

 

 

Map<String,Object> root = new HashMap<String,Object>();
root.put("username", "ajun");
templateEmail.sendTemplateMail(root, "xxx001@xxx.com", "主题标题", "demo.ftl");

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值