Spring的JavaMail实现异步发送邮件

具体背景就不说了,可以网上搜索相关知识,或者直接看Sping MailSender的官坊网页。这里就直接实战了(Java实现异步发送电子邮件,包含中文无乱码)。

Maven:

    <dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>javax.mail</artifactId>
      <version>1.5.0</version>
    </dependency>

ApplicationContext.xml:

    <!-- SET default mail properties -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.sina.com"/>
        <property name="protocol" value="smtp" /> 
        <!-- 465 for Gamil -->
        <property name="port" value="25"/>
        <property name="username" value="[email protected]"/>
        <property name="password" value="xxx"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.auth">true</prop>
                <!-- true for Gamil -->
                <prop key="mail.smtp.starttls.enable">false</prop>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>
     
    <!--Asyn send Eamil--> 
    <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">  
       <property name="corePoolSize" value="10"/>  
       <property name="maxPoolSize" value="30"/>  
    </bean>
 
    <!-- You can have some pre-configured messagess also which are ready to send -->
    <bean id="preConfiguredMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="to" value="[email protected]"></property>
        <property name="from" value="[email protected]"></property>
        <property name="subject" value="Test email from sina."/>
    </bean>

Email实体类:

package com.xxx;

import java.io.Serializable;

/**
 * @author 
 *
 */
public class ApplicationEmail implements Serializable {  
          
    public String getAddressee() {
        return addressee;
    }
    public void setAddressee(String addressee) {
        this.addressee = addressee;
    }
    public String getCc() {
        return cc;
    }
    public void setCc(String cc) {
        this.cc = cc;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    
    /**收件人**/  
    private String addressee;    
     /**抄送给**/   
    private String cc;    
     /**邮件主题**/  
    private String subject;   
      /**邮件内容**/  
    private String content;    
     /**附件**/   
    //private MultipartFile[] attachment = new MultipartFile[0];    
      
      
}  

异步邮件发送封装类:

package com.xxx;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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.stereotype.Service;

import com.xxx.Mailer;

/**
 * @author 
 *
 */
@Service
public class ApplicationMailer implements Mailer
{
    @Autowired
    private JavaMailSender mailSender;
     
    
    @Autowired
    private TaskExecutor taskExecutor;
    
    
    @Autowired
    private SimpleMailMessage preConfiguredMessage;
 
    
    /**
     * 同步发送邮件
     * 
     * @param email
     * @throws MessagingException
     * @throws IOException
     */
    public void sendMailBySynchronizationMode(ApplicationEmail email) throws MessagingException, IOException { 
         Session session=Session.getDefaultInstance(new Properties());
         MimeMessage mime= new MimeMessage(session);
         MimeMessageHelper helper = new MimeMessageHelper(mime, true, "utf-8");    
         helper.setFrom("[email protected]");//发件人    
         helper.setTo(InternetAddress.parse(email.getAddressee()));//收件人    
         //helper.setBcc("[email protected]");//暗送   
         helper.setReplyTo("[email protected]");//回复到   
         helper.setSubject(email.getSubject());//邮件主题    
         helper.setText(email.getContent(), true);//true表示设定html格式  
         
         mailSender.send(mime);
    }
    
    
    /**
     * 异步发送邮件
     * 
     * @param email
     */
    public void sendMailByAsynchronousMode(final ApplicationEmail email){  taskExecutor.execute(new Runnable(){    
         public void run(){      
        try {      
              sendMailBySynchronizationMode(email);   
             } catch (Exception e) {    
            }    
         }    
      });   
    }
}

public interface Mailer {
    public void sendMailByAsynchronousMode(final ApplicationEmail email);
}

调用Service异步发送邮件:

  @Autowired
  private Mailer mailer;

   //这是要异步发送邮件
   ApplicationEmail email = new ApplicationEmail();
   email.setAddressee("[email protected]");
   email.setSubject("测试邮件有一份");
   email.setContent("这个是内容html内容");
   mailer.sendMailByAsynchronousMode(email);

这里实现异步使用的是Task Execution,也可以用异步注解@Async,或者JMS(需要J2EE环境);如果需要调度可以用Quartz(使用场景如:每天2:00需要批量给会员发邮件)

如果要实现高可靠的高并发的异步邮件发送,可以用JMS或Queue,参考

本文结束。(干货分享:Spring和JavaMail发送邮件的经验.pdf

 

 

 

 

你可能感兴趣的:(javamail)