使用spring发送java mail 代码和配置说明

使用spring发送javaMail配置简单,功能强大,可以发送普通的文本邮件,也可以发送html邮件,和模板邮件,同时可以设置异步发送,减少主业务线程的等待时间,废话不说直接上类和配置文件。

首先上MailServicele类

package com.geelou.service;

 

import java.util.HashMap;

import java.util.Map;

 

import javax.mail.MessagingException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

 

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.springframework.core.task.TaskExecutor;

import org.springframework.mail.SimpleMailMessage;

import org.springframework.mail.javamail.JavaMailSender;

import org.springframework.mail.javamail.MimeMessageHelper;

import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

 

import com.geelou.pojo.User;

import com.geelou.util.ConfigUtil;

 

import freemarker.template.Configuration;

import freemarker.template.Template;

 

/**

 * 邮件服务

 * @author liqiang

 *

 */

public class MailService{

  protected final Log logger = LogFactory.getLog(getClass());

  private JavaMailSender javaMailSender;

  private Configuration freemarkerConfiguration;

  private TaskExecutor taskExecutor;

  

  private String encoding ="utf-8";

  private static String from = ConfigUtil.getValue("admin_mail");

  private static String fromName = ConfigUtil.getValue("admin_mail_name");

  private static InternetAddress fromAddress; 

  

  private InternetAddress getAddress(){

    if(fromAddress == null){

      try{

       fromAddress = new InternetAddress(from,fromName);

      }catch(Exception e){}

    }

   

    return fromAddress;

  }

  

  /**

   * 发送用户注册邮件

   * @param user

   */

  public void sendRegistMail(User user){

    Map<String, Object> parseMap = new HashMap<String, Object>();

    parseMap.put("user", user);

    setAsyncTemplateMail(user.getEmail(), "欢迎来到geelou专业个人网站",encoding, "registerok.html", parseMap);   

  }

  

  /**

   * 发送文本邮件

   */

  public void sendSimpleMail(String to,String subject,String text){

    SimpleMailMessage msg = new SimpleMailMessage();

    msg.setFrom(from);

    msg.setTo(to);

    msg.setSubject(subject);

    msg.setText(text);

    javaMailSender.send(msg);   

  }

  

  /**

   * 异步发送模版邮件

   * @param to

   * @param subject

   * @param encoding

   * @param template

   * @param parse

   * @throws Exception

   */

  public void setAsyncTemplateMail(final String to,final String subject,final String encoding,final String template,final Map<String,Object> parse){

    taskExecutor.execute(new Runnable() {

      public void run(){

       try{

         setTemplateMail(to,subject,encoding,template,parse);

       }catch (Exception e) {

         logger.error("邮件发送失败,失败提示:"+e.getMessage());

       }

      }

    }

    );  

  }

  

  /**

   * 发送模版邮件

   * @param to

   * @param subject

   * @param encoding

   * @param template

   * @param parse

   * @throws Exception

   */

  public void setTemplateMail(String to,String subject,String encoding,String template,Map<String,Object> parse)throws Exception{

    Template templateS = freemarkerConfiguration.getTemplate(template, encoding);

   

    String htmlCnt = FreeMarkerTemplateUtils.processTemplateIntoString(templateS, parse);

   

    sendHTMLMail(to,subject,htmlCnt,encoding);

  }

  

  /**

   * 发送html格式邮件

   * @param to

   * @param subject

   * @param htmlCnt

   * @param encoding

   * @throws MessagingException

   */

  public void sendHTMLMail(String to,String subject,StringBuffer htmlCnt,String encoding)throws MessagingException{

    sendHTMLMail(to,subject,htmlCnt.toString(),encoding);

  }

  

  /**

   * 发送html格式邮件

   * @param to

   * @param subject

   * @param htmlCnt

   * @param encoding

   * @throws MessagingException

   */

  public void sendHTMLMail(String to,String subject,String htmlCnt,String encoding)throws MessagingException{

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,false,encoding);

    mimeMessageHelper.setFrom(getAddress());

    mimeMessageHelper.setTo(to);

    mimeMessageHelper.setBcc(getAddress());

    mimeMessageHelper.setSubject(subject);

    mimeMessageHelper.setText(htmlCnt,true);

   

    javaMailSender.send(mimeMessage);

  }

  

  public void setJavaMailSender(JavaMailSender javaMailSender){

    this.javaMailSender = javaMailSender;

  }

 

  public void setFreemarkerConfiguration(Configuration freemarkerConfiguration) {

    this.freemarkerConfiguration = freemarkerConfiguration;

  }

 

 

  public void setTaskExecutor(TaskExecutor taskExecutor) {

    this.taskExecutor = taskExecutor;

  }

}

 

 

下面是 spring applicationContext.xml里面关于mail的配置

<!-- email有关配置 -->

  <!-- 配置异步发送器 -->

  <bean id="taskExecutor"class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">

    <property name="corePoolSize"value="10"/>

    <property name="maxPoolSize"value="30"/>

  </bean>

  <!-- 配置邮件模板相关信息 -->

  <bean id="freemarkerConfiguration"class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">

    <property name="templateLoaderPath"value="classpath:/com/mcp/service/mail"/>

  </bean>

  <!-- 配置spring的javamail -->

  <bean id="javaMailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl">

    <!-- smtp地址 -->

    <property name="host"value="smtp.gmail.com"></property> 

    <!-- 端口 -->

    <property name="port"value="465"></property> 

    <!-- 邮件发送地址 -->

    <property name="username"value="admin@geelou.com"></property>

    <!-- 发送密码 -->

    <property name="password"value="aaaaaa"></property> 

    <!-- 发送时使用的字符集 -->

    <property name="defaultEncoding"value="UTF-8"></property> 

    <!-- javaMail相关参数设置 -->

    <property name="javaMailProperties"> 

      <props> 

       <!-- 发送模式 debug -->

        <prop key="mail.debug">true</prop> 

        <!-- 指定ssl -->

        <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> 

        <!-- 是否需要auth认证 -->

        <prop key="mail.smtp.auth">true</prop> 

      </props> 

    </property>

  </bean>





http://www.geelou.com/article/100.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值