使用spring javamail smtp发送html邮件

      最近项目中使用到了spring javamail进行定时邮件发送,网上的例子质量参差不齐,说的不是很清楚,这里简单的介绍自己写的程序,一是与大家分享,另外做为笔记供自己以后参考。

      1. 首先我们看在spring中如何配置javamail

  
  
  
  
  1. <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> 
  2.     <property name="host" value="${metrix.smtp.server}" /> 
  3.     <property name="port" value="${metrix.smtp.port}" /> 
  4.     <property name="username" value="${metrix.smtp.user}" /> 
  5.     <property name="password" value="${metrix.smtp.password}" /> 
  6.     <property name="javaMailProperties"> 
  7.         <props> 
  8.             <prop key="mail.smtp.auth">${metrix.smtp.auth}</prop> 
  9.             <prop key="mail.smtp.timeout">${metrix.smtp.timeout}</prop> 
  10.         </props> 
  11.     </property> 
  12. </bean> 
  
  
  
  
  1. <bean id="mimeMessageHelperAdapter" class="com.alibaba.corp.metrix.admin.biz.dataprocess.utils.MimeMessageHelperAdapter"> 
  2.     <property name="from" value="${metrix.smtp.from.address}"/> 
  3.     <property name="tos" value="${metrix.smtp.to.address}"/> 
  4.     <property name="personal" value="${metrix.smtp.from.personal}"/> 
  5. </bean> 

    如果你的smtp邮件服务器不需要认证,可以将properties中mail.smtp.auth设置为false.

    2. 为了便于设置MimeMessageHelper的属性,定义了一个MimeMessageHelperAdapter类,在spring中进行配置,代码如下

  
  
  
  
  1. package com.alibaba.corp.metrix.admin.biz.dataprocess.utils; 
  2.  
  3. /** 
  4.  * Copyright 1999-2100 Alibaba.com All right reserved. This software is the 
  5.  * confidential and proprietary information of Alibaba.com 
  6.  * ("Confidential Information"). You shall not disclose such Confidential 
  7.  * Information and shall use it only in accordance with the terms of the license 
  8.  * agreement you entered into with Alibaba.com. 
  9.  * 
  10.  * @Author: leon Mao 
  11.  * @Date: 07/13/2012 
  12.  * @Time: 11:49 
  13.  * @Description: 
  14.  */ 
  15.  
  16. import org.apache.commons.lang.StringUtils; 
  17. import org.slf4j.Logger; 
  18. import org.slf4j.LoggerFactory; 
  19.  
  20. public class MimeMessageHelperAdapter { 
  21.     Logger logger = LoggerFactory.getLogger(MimeMessageHelperAdapter.class); 
  22.     private String from; 
  23.     private String tos; 
  24.     private String personal; 
  25.  
  26.     public String getFrom() { 
  27.         return from; 
  28.     } 
  29.  
  30.     public void setFrom(String from) { 
  31.         this.from = from; 
  32.     } 
  33.  
  34.     public String getTos() { 
  35.         return tos; 
  36.     } 
  37.  
  38.     public String[] getTosArray() { 
  39.         if (this.tos != null) { 
  40.             return StringUtils.split(this.tos, ','); 
  41.         } else { 
  42.             logger.warn("email receiver(s) not configured yet!"); 
  43.             return null
  44.         } 
  45.     } 
  46.  
  47.     public void setTos(String tos) { 
  48.         this.tos = tos; 
  49.     } 
  50.  
  51.     public String getPersonal() { 
  52.         return personal; 
  53.     } 
  54.  
  55.     public void setPersonal(String personal) { 
  56.         this.personal = personal; 
  57.     } 

   3. 定义mailsender工具类

  
  
  
  
  1. package com.alibaba.corp.metrix.admin.biz.dataprocess.utils; 
  2.  
  3. import java.io.UnsupportedEncodingException; 
  4.  
  5. import javax.mail.MessagingException; 
  6. import javax.mail.internet.MimeMessage; 
  7.  
  8. import org.springframework.mail.javamail.JavaMailSenderImpl; 
  9. import org.springframework.mail.javamail.MimeMessageHelper; 
  10.  
  11. import com.alibaba.corp.metrix.admin.biz.dataprocess.job.base.BeanFactoryUtil; 
  12.  
  13. /** 
  14.  * Copyright 1999-2100 Alibaba.com All right reserved. This software is the 
  15.  * confidential and proprietary information of Alibaba.com 
  16.  * ("Confidential Information"). You shall not disclose such Confidential 
  17.  * Information and shall use it only in accordance with the terms of the license 
  18.  * agreement you entered into with Alibaba.com. 
  19.  *  
  20.  * @Author: leon Mao 
  21.  * @Date: 07/13/2012 
  22.  * @Time: 12:01 
  23.  * @Description: 
  24.  */ 
  25. public class MailSenderUtil { 
  26.     public static void sendMail(String subject, String content, Boolean html, String[] tos) 
  27.             throws MessagingException, UnsupportedEncodingException { 
  28.         JavaMailSenderImpl javaMailSender = (JavaMailSenderImpl) BeanFactoryUtil 
  29.                 .getBean("mailSender"); 
  30.         MimeMessageHelperAdapter mimeMessageHelperAdapter = (MimeMessageHelperAdapter) BeanFactoryUtil 
  31.                 .getBean("mimeMessageHelperAdapter"); 
  32.  
  33.         MimeMessage message = javaMailSender.createMimeMessage(); 
  34.         MimeMessageHelper helper = new MimeMessageHelper(message, true, "GBK"); 
  35.         helper.setFrom(mimeMessageHelperAdapter.getFrom(), mimeMessageHelperAdapter.getPersonal()); 
  36.         helper.setSubject(subject); 
  37.         if (tos == null || tos.length == 0) { 
  38.             helper.setTo(mimeMessageHelperAdapter.getTosArray()); 
  39.         } else { 
  40.             helper.setTo(tos);//推送Job中meta-info中设定的邮件接收者 
  41.         } 
  42.         helper.setText(content, html); 
  43.         javaMailSender.send(message); 
  44.     } 

    这里sendMail方法中的html参数定义mime类型,这样outlook等邮件客户端会将收到的内容自动以html解析。

    4. 由于邮件的内容及长度不同,如果硬编码内容在java代码中,往往使得代码丑陋,也不够灵活,所以我们可以使用Velocity来渲染邮件内容。

  
  
  
  
  1. public class MailContentGenerator { 
  2.     public static final String PREFIX = "classpath:result/"
  3.  
  4.     public static String generateMailContent(List results, String vmName) throws IOException { 
  5.         VelocityContext context = new VelocityContext(); 
  6.         context.put("results", results); 
  7.  
  8.         Reader reader = new InputStreamReader(Resources.getResourceAsStream(PREFIX + vmName), 
  9.                 "GBK"); 
  10.         StringWriter writer = new StringWriter(1024 * 512); 
  11.         Velocity.evaluate(context, writer, "", reader); 
  12.         return writer.toString(); 
  13.     } 

  5. velocity模板的例子

  
  
  
  
  1. <html> 
  2. <head> 
  3.     <meta http-equiv="Content-Type" content="text/html; charset=GBK"/> 
  4.     <style type="text/css"> 
  5.         thead tr { 
  6.             background-color: ActiveCaption; 
  7.             color: CaptionText; 
  8.         } 
  9.  
  10.         th, td { 
  11.             vertical-align: top; 
  12.             font-family: "Tahoma"; 
  13.             font-size: 10pt; 
  14.             padding: 3px; 
  15.         } 
  16.  
  17.         table, th, td { 
  18.             border: 1px solid silver; 
  19.         } 
  20.  
  21.         table { 
  22.             border-collapse: collapse; 
  23.         } 
  24.     </style> 
  25.  
  26. </head> 
  27. <body> 
  28. <div style="font-size:12pt;"> 
  29.     <table> 
  30.         <tbody> 
  31.         <tr> 
  32.             <th>序号</th> 
  33.             <th>标题</th> 
  34.             <th>产品线</th> 
  35.             <th>团队</th> 
  36.             <th>开发</th> 
  37.             <th>QA</th> 
  38.             <th>PE</th> 
  39.             <th>发布包</th> 
  40.             <th>上线手册</th> 
  41.             <th>上线时间</th> 
  42.         </tr> 
  43.             #foreach ($result in $results) 
  44.             <tr> 
  45.                 <td>$velocityCount</td> 
  46.                 #foreach ($element in $result) 
  47.                     <td>$!element</td> 
  48.                 #end 
  49.             </tr> 
  50.             #end 
  51.         </tbody> 
  52.     </table> 
  53. </div> 
  54. </body> 
  55. </html> 

     6. 主要依赖的包

      spring、misc.mail、java.servlet、jakarta.velocity

你可能感兴趣的:(spring,velocity,smtp,javamail)