spring mail 发送邮件

时间:2022-09-24 09:08:43

  介绍 如何使用Spring mail api 来发送email,用velocityEngine 解析邮件模板,这里会用一个完整的Spring mail 发送邮件的例子来演示它发送email的过程。您会欣赏到 Spring mail 的丰富功能,以及它是如何简化开发任务的. 

Spring Mail API 
Spring Mail API都在org.springframework.mail及其子包org.springframework.mail.javamail中封装。 

JavaMailSenderImpl: 邮件发送器,主要提供了邮件发送接口、透明创建Java Mail的MimeMessage、及邮件发送的配置(如:host/port/username/password...)。 
MimeMailMessage、MimeMessageHelper:对MimeMessage进行了封装。Spring还提供了一个回调接口MimeMessagePreparator, 用于准备JavaMail的MIME信件. 

上代码,MailUtil类负责发送,MailBean类封装邮件信息。只有这两个类了简单吧 

MailUtil.java 

Java代码   spring mail 发送邮件
  1. package com.dr.sm.mail;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.StringWriter;  
  5. import java.io.UnsupportedEncodingException;  
  6.   
  7. import javax.mail.MessagingException;  
  8. import javax.mail.internet.MimeMessage;  
  9.   
  10. import org.apache.log4j.Logger;  
  11. import org.apache.velocity.VelocityContext;  
  12. import org.apache.velocity.app.VelocityEngine;  
  13. import org.apache.velocity.exception.VelocityException;  
  14. import org.springframework.mail.javamail.JavaMailSender;  
  15. import org.springframework.mail.javamail.MimeMessageHelper;  
  16.   
  17. /** 
  18.  * spring发送mail工具 
  19.  * @author: haleywang,@created on: 2012-9-20 
  20.  */  
  21. public class MailUtil {  
  22.   
  23.     Logger log = Logger.getLogger(MailUtil.class);  
  24.       
  25.     private JavaMailSender javaMailSender;  
  26.     private VelocityEngine velocityEngine;          //模板解析  
  27.       
  28.       
  29.     /** 
  30.      * @param mailBean 
  31.      * @return 
  32.      * @throws MessagingException 
  33.      */  
  34.     public boolean send(MailBean mailBean) throws MessagingException {  
  35.   
  36.         MimeMessage msg = createMimeMessage(mailBean);  
  37.         if(msg == null){  
  38.             return false;  
  39.         }  
  40.           
  41.         this.sendMail(msg, mailBean);  
  42.           
  43.         return true;  
  44.     }  
  45.       
  46.     private void sendMail(MimeMessage msg, MailBean mailBean){  
  47.                 javaMailSender.send(msg);  
  48.                 log.info("$$$ Send mail Subject:" +  mailBean.getSubject()   
  49.                         + ", TO:" + arrayToStr(mailBean.getToEmails()) );  
  50.   
  51.     }  
  52.       
  53.     /* 
  54.      * 记日记用的 
  55.      */  
  56.     private String arrayToStr(String[] array){  
  57.         if(array == null || array.length == 0){  
  58.             return null;  
  59.         }  
  60.         StringBuffer sb = new StringBuffer();  
  61.         for(String str : array){  
  62.             sb.append(str+" , ") ;  
  63.         }  
  64.         return sb.toString();  
  65.     }  
  66.   
  67.     /*  
  68.      * 根据 mailBean 创建 MimeMessage 
  69.      */  
  70.     private MimeMessage createMimeMessage(MailBean mailBean) throws MessagingException {  
  71.         if (!checkMailBean(mailBean)) {  
  72.             return null;  
  73.         }  
  74.         String text = getMessage(mailBean);  
  75.         if(text == null){  
  76.             log.warn("@@@ warn mail text is null (Thread name="   
  77.                     + Thread.currentThread().getName() + ") @@@ " +  mailBean.getSubject());  
  78.             return null;  
  79.         }  
  80.         MimeMessage msg = javaMailSender.createMimeMessage();  
  81.         MimeMessageHelper messageHelper = new MimeMessageHelper(msg, true, "UTF-8");  
  82.         //messageHelper.setFrom(mailBean.getFrom());  
  83.         try {  
  84.             messageHelper.setFrom(mailBean.getFrom(), mailBean.getFromName());  
  85.         } catch (UnsupportedEncodingException e) {  
  86.             log.error(e);  
  87.   
  88.         }  
  89.         messageHelper.setSubject(mailBean.getSubject());  
  90.         messageHelper.setTo(mailBean.getToEmails());  
  91.         messageHelper.setText(text, true); // html: true  
  92.           
  93.         return msg;  
  94.     }  
  95.       
  96.     /* 
  97.      * 模板解析 
  98.      * @param mailBean 
  99.      * @return 
  100.      */  
  101.     private String getMessage(MailBean mailBean) {  
  102.         StringWriter writer = null;  
  103.         try {  
  104.   
  105.             writer = new StringWriter();  
  106.             VelocityContext context = new VelocityContext(mailBean.getData());  
  107.   
  108.             velocityEngine.evaluate(context, writer, "", mailBean.getTemplate());  
  109.   
  110.             return writer.toString();  
  111.         } catch (VelocityException e) {  
  112.             log.error(" VelocityException : " + mailBean.getSubject() + "\n" + e);  
  113.         } catch (IOException e) {  
  114.             log.error(" IOException : " + mailBean.getSubject() + "\n" + e);  
  115.         } finally {  
  116.             if (writer != null) {  
  117.                 try {  
  118.                     writer.close();  
  119.                 } catch (IOException e) {  
  120.                     log.error("###StringWriter close error ... ");  
  121.                 }  
  122.             }  
  123.         }  
  124.         return null;  
  125.     }  
  126.       
  127.     /* 
  128.      * check 邮件 
  129.      */  
  130.     private boolean checkMailBean(MailBean mailBean){  
  131.         if (mailBean == null) {  
  132.             log.warn("@@@ warn mailBean is null (Thread name="   
  133.                     + Thread.currentThread().getName() + ") ");  
  134.             return false;  
  135.         }  
  136.         if (mailBean.getSubject() == null) {  
  137.             log.warn("@@@ warn mailBean.getSubject() is null (Thread name="   
  138.                     + Thread.currentThread().getName() + ") ");  
  139.             return false;  
  140.         }  
  141.         if (mailBean.getToEmails() == null) {  
  142.             log.warn("@@@ warn mailBean.getToEmails() is null (Thread name="   
  143.                     + Thread.currentThread().getName() + ") ");  
  144.             return false;  
  145.         }  
  146.         if (mailBean.getTemplate() == null) {  
  147.             log.warn("@@@ warn mailBean.getTemplate() is null (Thread name="   
  148.                     + Thread.currentThread().getName() + ") ");  
  149.             return false;  
  150.         }  
  151.         return true;  
  152.     }  
  153.   
  154.       
  155.     /*===================== setter & getter =======================*/  
  156.     public void setJavaMailSender(JavaMailSender javaMailSender) {  
  157.         this.javaMailSender = javaMailSender;  
  158.     }  
  159.   
  160.     public void setVelocityEngine(VelocityEngine velocityEngine) {  
  161.         this.velocityEngine = velocityEngine;  
  162.     }  
  163.   
  164. }  

 

MailBean 

Java代码   spring mail 发送邮件
  1. package com.dr.sm.mail;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Map;  
  5.   
  6.   
  7. public class MailBean implements Serializable {  
  8.   
  9.     private String from;  
  10.     private String fromName;  
  11.     private String[] toEmails;  
  12.       
  13.     private String subject;  
  14.       
  15.     private Map data ;          //邮件数据  
  16.     private String template;    //邮件模板  
  17.       
  18.       
  19.     //省略setter&getter方法  
  20.       
  21. }  

接着就是配置文件了,applicationContext.xml,applicationContext-mail.xml 
applicationContext.xml 

Xml代码   spring mail 发送邮件
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:p="http://www.springframework.org/schema/p"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xmlns:tx="http://www.springframework.org/schema/tx"  
  8.     xmlns:context="http://www.springframework.org/schema/context"  
  9.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  10.                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  11.                         http://www.springframework.org/schema/aop  
  12.                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  13.                         http://www.springframework.org/schema/tx  
  14.                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  15.                         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd  
  16.                         ">  
  17.   
  18.     <!-- ================2.自动扫描的包名===================== -->  
  19.     <context:component-scan base-package="com.dr.sm" />   
  20.   
  21.     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  22.         <property name="locations">  
  23.             <list>  
  24.                 <value>classpath:mail.properties</value>  
  25.             </list>  
  26.         </property>  
  27.     </bean>  
  28.       
  29.       
  30.     <import resource="classpath:applicationContext-mail.xml"/>  
  31.       
  32. </beans>  


applicationContext-mail.xml 

Java代码   spring mail 发送邮件
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:p="http://www.springframework.org/schema/p"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xmlns:tx="http://www.springframework.org/schema/tx"  
  8.     xmlns:context="http://www.springframework.org/schema/context"  
  9.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  10.                         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  11.                         http://www.springframework.org/schema/aop  
  12.                         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  13.                         http://www.springframework.org/schema/tx  
  14.                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  15.                         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd  
  16.                         ">  
  17.   
  18.     <!-- 邮件发送器 163  -->  
  19.     <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
  20.         <property name="host" value="${mail.host}" />  
  21.         <property name="username" value="${mail.username}" />  
  22.         <property name="password" value="${mail.password}" />  
  23.         <property name="defaultEncoding" value="UTF-8"></property>  
  24.         <property name="javaMailProperties">  
  25.             <props>  
  26.                 <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>  
  27.                 <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>  
  28.             </props>  
  29.         </property>  
  30.     </bean>  
  31.       
  32.       
  33.       
  34.     <!--  邮件发送器 gmail    
  35.     <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">    
  36.         <property name="host" value="${mail.host}" />  
  37.         <property name="username" value="${mail.username}" />  
  38.         <property name="password" value="${mail.password}" />  
  39.         <property name="defaultEncoding" value="UTF-8"></property>  
  40.         <property name="javaMailProperties">    
  41.             <props>    
  42.                 <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>  
  43.                 <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>  
  44.                 <prop key="mail.smtp.port">465</prop>    
  45.                 <prop key="mail.smtp.socketFactory.port">465</prop>    
  46.                 <prop key="mail.smtp.socketFactory.fallback">false</prop>    
  47.                 <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>    
  48.             </props>    
  49.         </property>    
  50.     </bean>    
  51.     -->  
  52.       
  53.   
  54.     <bean id="velocityEngine"  
  55.         class="org.springframework.ui.velocity.VelocityEngineFactoryBean">  
  56.     </bean>  
  57.   
  58.     <bean id="mailUtil" class="com.dr.sm.mail.MailUtil">  
  59.         <property name="javaMailSender" ref="mailSender"></property>  
  60.         <property name="velocityEngine" ref="velocityEngine"></property>  
  61.     </bean>  
  62.       
  63.   
  64. </beans>  


mail.properties 
Java代码   spring mail 发送邮件
  1. mail.from=wzqdemo@163.com  
  2. mail.host=smtp.163.com  
  3. mail.password=********  
  4. mail.smtp.auth=true  
  5. mail.smtp.timeout=25000  
  6. mail.username=wzqdemo  
  7.   
  8. #mail.from=wzqdemo@163.com  
  9. #mail.host=smtp.gmail.com  
  10. #mail.password=********  
  11. #mail.smtp.auth=true  
  12. #mail.smtp.timeout=25000  
  13. #mail.username=wzqdemo@gmail.com  


jar包: 
Java代码   spring mail 发送邮件
  1. activation.jar  
  2. commons-collections-3.2.jar  
  3. commons-lang-2.3.jar  
  4. commons-logging-1.1.1.jar  
  5. junit-4.10.jar  
  6. log4j-1.2.15.jar  
  7. mail.jar  
  8. spring-asm-3.0.6.RELEASE.jar  
  9. spring-beans-3.0.6.RELEASE.jar  
  10. spring-context-3.0.6.RELEASE.jar  
  11. spring-context-support-3.0.6.RELEASE.jar  
  12. spring-context.jar  
  13. spring-core-3.0.6.RELEASE.jar  
  14. spring-expression-3.0.6.RELEASE.jar  
  15. spring-jdbc-3.0.6.RELEASE.jar  
  16. spring-test-3.0.6.RELEASE.jar  
  17. spring-tx-3.0.6.RELEASE.jar  
  18. spring-xml-1.5.10.jar  
  19. velocity-1.6.4.jar  


ok,终于可以开始测试咯! 
Java代码   spring mail 发送邮件
  1. package com.dr.sm.mail;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import javax.annotation.Resource;  
  7. import javax.mail.MessagingException;  
  8.   
  9. import org.junit.Test;  
  10. import org.springframework.test.context.ContextConfiguration;  
  11. import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
  12.   
  13.   
  14. @ContextConfiguration("classpath:applicationContext.xml")  
  15. public class MailServiceTest extends AbstractJUnit4SpringContextTests {  
  16.         
  17.     @Resource  
  18.     private MailUtil mailUtil;  
  19.   
  20.     @Test  
  21.     public void testSendMail() {  
  22.           
  23.         //创建邮件  
  24.         MailBean mailBean = new MailBean();  
  25.         mailBean.setFrom("wzqdemo@163.com");  
  26.         mailBean.setSubject("hello world");  
  27.         mailBean.setToEmails(new String[]{"wzqdemo@gmail.com"});  
  28.         mailBean.setTemplate("hello ${userName} !<a href='www.baidu.com' >baidu</a>");  
  29.         Map map = new HashMap();  
  30.         map.put("userName", "Haley Wang");  
  31.         mailBean.setData(map);  
  32.           
  33.         //发送邮件  
  34.         try {  
  35.             mailUtil.send(mailBean);  
  36.         } catch (MessagingException e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.           
  40.     }