---
title: "Spring邮件发送（可带附件，模板，群发，异步发送等功能）"
author: "paskaa"
date: "2011-09-20T16:19:48Z"
tags: []
categories: ["Web前端"]
slug: "spring"
draft: false
lastmod: "2011-09-20T16:20:16Z"
id: 1176002
url: "https://paskaa.iteye.com/blog/1176002"
---

### [](http://mengqingyu.iteye.com/blog/389273)

- **博客分类：**
- [JavaEE](http://mengqingyu.iteye.com/category/65567)

[Spring](http://www.iteye.com/blogs/tag/Spring) [freemarker](http://www.iteye.com/blogs/tag/freemarker) [XML](http://www.iteye.com/blogs/tag/XML) [HTML](http://www.iteye.com/blogs/tag/HTML) [UI](http://www.iteye.com/blogs/tag/UI)

以下是我对spring发送邮件的总结：  
分别使用了两种方法：单例模式和属性全注入的方法。  
发送模式又分为：单发，群发。  
可发送：text，html模板，附件等。  
**1、单例模式（单发，群发text）**  
在classpath底下新建application-mail.xml，内容如下：  
**Xml代码：**

Java代码  [![收藏代码](http://mengqingyu.iteye.com/images/icon_star.png)]()

01. &lt;?xml version= "1.0"  encoding= "UTF-8" ?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:aop="http://www.springframework.org/schema/aop"
05. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
06. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"&gt;
07. &lt;!-- 注意:这里的参数(如用户名、密码)都是针对邮件发送者的 --&gt;
08. &lt;bean id="mailSender"
09. class = "org.springframework.mail.javamail.JavaMailSenderImpl" &gt;
10. &lt;property name="host" &gt;
11. &lt;value&gt;smtp.163 .com&lt;/value&gt;
12. &lt;/property&gt;
13. &lt;property name="javaMailProperties" &gt;
14. &lt;props&gt;
15. &lt;prop key="mail.smtp.auth" &gt; true &lt;/prop&gt;
16. &lt;prop key="mail.smtp.timeout" &gt; 25000 &lt;/prop&gt;
17. &lt;/props&gt;
18. &lt;/property&gt;
19. &lt;property name="username" &gt;
20. &lt;value&gt;username@163 .com&lt;/value&gt;
21. &lt;/property&gt;
22. &lt;property name="password" &gt;
23. &lt;value&gt;password&lt;/value&gt;
24. &lt;/property&gt;
25. &lt;/bean&gt;
26. &lt;/beans&gt;

或者把以上的Beans配置到applicaiont.xml里面也可以。  
发送text格式的Email类：

Java代码  [![收藏代码](http://mengqingyu.iteye.com/images/icon_star.png)]()

01. /
02. import  org.springframework.context.ApplicationContext;
03. import  org.springframework.context.support.ClassPathXmlApplicationContext;
04. import  org.springframework.mail.SimpleMailMessage;
05. import  org.springframework.mail.javamail.JavaMailSender;
06. public   class  EmailUtil {
07. private   static  EmailUtil emailUtil =  null ;
08. public  ApplicationContext ctx =  null ;
09. private  EmailUtil() {
10. //获取上下文
11. ctx = new  ClassPathXmlApplicationContext( "applicationContext-mail.xml" );
12. }
13. /\**
14. \*
15. * @function:获得单例
16. \*/
17. public   static  EmailUtil getInstance()
18. {
19. if (emailUtil== null )
20. {
21. synchronized  (EmailUtil. class )
22. {
23. if (emailUtil== null ) {
24. emailUtil = new  EmailUtil();
25. }
26. }
27. }
28. return  emailUtil;
29. }
30. public   void  sentEmails(String emails,String subject,String text)
31. {
32. //获取JavaMailSender bean
33. JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender" );
34. //SimpleMailMessage只能用来发送text格式的邮件
35. SimpleMailMessage mail = new  SimpleMailMessage();
36. String email\[] = emails.split(";" );
37. for ( int  i= 0 ;i&lt;email.length;i++) {
38. try  {
39. mail.setTo(email\[i]);//接受者
40. mail.setFrom("username@163.com" );
41. mail.setSubject(subject);//主题
42. mail.setText(text);//邮件内容
43. sender.send(mail);
44. } catch  (Exception e) {
45. e.printStackTrace();
46. }
47. }
48. }
49. /\**
50. * @function:测试邮件发送
51. \*/
52. public   static   void  main(String\[] args) {
53. String  mail\_title  = "注册成功" ;
54. String  mail\_content    = "恭喜!您已经注册成功.&lt;BR&gt;欢迎使用本网站,主页地址:&lt;a href='http://www.baidu.com'/&gt;" ;
55. EmailUtil email = EmailUtil.getInstance();
56. email.sentEmails("username@163.com" ,mail\_title,mail\_content);
57. }
58. }

2.属性全注入的方法（单发，群发html模板）  
FreeMarker是一个被广泛使用的模板框架，Spring可以很好的支持该框架。Spring为FreeMarker提供了一个 FreeMarkerConfigurer类，通过此类可方便地创建FreeMarker的基础环境，Spring提供 FreeMarkerTemplateUtils工具类来完成解析模板的任务。下面以用户注册成功后发送的模板文件 registerUser.ftl,${content}标签代表一个可被替换的动态属性。FreeMarker模板的标签支持级联属性， 如${user.id}则表示user对象的id属性。在配置文件中已设置好模板目录，所以可在类中直接用模板文件名来定位模板文件。模板文件用UTF- 8编码格式，避免中文乱码。通过设置template\_update\_delay属性，可让FreeMarker定期刷新模板，从而使应用程序在不重启下 更新模板。

Html代码  [![收藏代码](http://mengqingyu.iteye.com/images/icon_star.png)]()

1. &lt; html &gt;
2. &lt; head &gt;
3. &lt; meta   http-equiv = "content-type"   content = "text/html;charset=utf8" &gt;
4. &lt;/ head &gt;
5. &lt; body &gt;
6. 恭喜您成功注册！您的用户名为：&lt; font   color = 'red'   size = '30' &gt; ${content} &lt;/ font &gt;
7. &lt;/ body &gt;
8. &lt;/ html &gt;

 

Xml代码  [![收藏代码](http://mengqingyu.iteye.com/images/icon_star.png)]()

01. &lt;? xml   version = "1.0"   encoding = "UTF-8" ?&gt;
02. &lt; beans   xmlns = "http://www.springframework.org/schema/beans"
03. xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:aop = "http://www.springframework.org/schema/aop"
05. xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
06. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"&gt;
07. &lt;!-- 注意:这里的参数(如用户名、密码)都是针对邮件发送者的 --&gt;
08. &lt; bean   id = "mailSender"
09. class = "org.springframework.mail.javamail.JavaMailSenderImpl" &gt;
10. &lt; property   name = "host" &gt;
11. &lt; value &gt; smtp.163.com &lt;/ value &gt;
12. &lt;/ property &gt;
13. &lt; property   name = "javaMailProperties" &gt;
14. &lt; props &gt;
15. &lt; prop   key = "mail.smtp.auth" &gt; true &lt;/ prop &gt;
16. &lt; prop   key = "mail.smtp.timeout" &gt; 25000 &lt;/ prop &gt;
17. &lt;/ props &gt;
18. &lt;/ property &gt;
19. &lt; property   name = "username" &gt;
20. &lt; value &gt; username@163.com &lt;/ value &gt;
21. &lt;/ property &gt;
22. &lt; property   name = "password" &gt;
23. &lt; value &gt; password &lt;/ value &gt;
24. &lt;/ property &gt;
25. &lt;/ bean &gt;
26. &lt;/ beans &gt;
27. &lt; bean   id = "freeMarker"   class = "org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" &gt;
28. &lt; property   name = "templateLoaderPath"   value = "classpath:mailTemplate" /&gt; &lt;!--指定模板文件目录--&gt;
29. &lt; property   name = "freemarkerSettings" &gt; &lt;!-- 设置FreeMarker环境属性--&gt;
30. &lt; props &gt;
31. &lt; prop   key = "template\_update\_delay" &gt; 1800 &lt;/ prop &gt; &lt;!--刷新模板的周期，单位为秒--&gt;
32. &lt; prop   key = "default\_encoding" &gt; UTF-8 &lt;/ prop &gt; &lt;!--模板的编码格式 --&gt;
33. &lt; prop   key = "locale" &gt; zh\_CN &lt;/ prop &gt; &lt;!-- 本地化设置--&gt;
34. &lt;/ props &gt;
35. &lt;/ property &gt;
36. &lt;/ bean &gt;
37. &lt;!-- \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**           Email Service配置         \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** --&gt;
38. &lt; bean   id = "emailService"   class = "EmailService" &gt;
39. &lt; property   name = "sender"   ref = "mailSender" &gt; &lt;/ property &gt;
40. &lt; property   name = "freeMarkerConfigurer"   ref = "freeMarker" &gt; &lt;/ property &gt;
41. &lt;/ bean &gt;
42. &lt;/ beans &gt;

 

Java代码  [![收藏代码](http://mengqingyu.iteye.com/images/icon_star.png)]()

01. import  javax.mail.MessagingException;
02. import  org.springframework.mail.javamail.JavaMailSender;
03. import  org.springframework.ui.freemarker.\*;
04. import  org.springframework.web.servlet.view.freemarker.\*;
05. import  freemarker.template.\*;
06. public   abstract   class  EmailAbstract {
07. protected  String from;
08. protected  String subject;
09. protected  JavaMailSender sender;
10. protected  FreeMarkerConfigurer freeMarkerConfigurer= null ;  //FreeMarker的技术类
11. public  String getFrom() {
12. return  from;
13. }
14. public   void  setFrom(String from) {
15. this .from = from;
16. }
17. public  String getSubject() {
18. return  subject;
19. }
20. public   void  setSubject(String subject) {
21. this .subject = subject;
22. }
23. public  JavaMailSender getSender() {
24. return  sender;
25. }
26. public   void  setSender(JavaMailSender sender) {
27. this .sender = sender;
28. }
29. public   void  setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
30. this .freeMarkerConfigurer = freeMarkerConfigurer;
31. }
32. /\**
33. * 发送单个html格式邮件
34. \*/
35. public   abstract   void  sendEmail(String content,String address);
36. /\**
37. * 批量发送html格式邮件
38. \*/
39. public   abstract   void  sendBatchEmail(String content,List&lt;String&gt; address);
40. }

 

Java代码  [![收藏代码](http://mengqingyu.iteye.com/images/icon_star.png)]()

01. import  javax.mail.Message;
02. import  javax.mail.MessagingException;
03. import  javax.mail.internet.InternetAddress;
04. import  javax.mail.internet.MimeMessage;
05. import  org.springframework.mail.javamail.MimeMessageHelper;
06. import  org.springframework.ui.freemarker.\*;
07. import  org.springframework.web.servlet.view.freemarker.\*;
08. import  freemarker.template.\*;
09. public   class  EmailService  extends  EmailAbstract {
10. /\**
11. * 发送带模板的单个html格式邮件
12. \*/
13. public   void  sendMessage(String content,String address)  throws  MessagingException {
14. MimeMessage msg = sender.createMimeMessage();
15. //设置utf-8或GBK编码，否则邮件会有乱码，true表示为multipart邮件
16. MimeMessageHelper helper = new  MimeMessageHelper(msg,  true ,  "utf-8" );
17. helper.setTo(address);    //邮件接收地址
18. helper.setFrom(from);   //邮件发送地址,这里必须和xml里的邮件地址相同一致
19. helper.setSubject(subject);   //主题
20. String htmlText = getMailText(content);   //使用模板生成html邮件内容
21. helper.setText(htmlText, true );    //邮件内容，注意加参数true，表示启用html格式
22. sender.send(msg); //发送邮件
23. }
24. /\**
25. * 批量发送带附件的html格式邮件
26. \*/
27. public   void  sendBatchEmail(String content,List&lt;String&gt; address)  throws  MessagingException {
28. MimeMessage msg = sender.createMimeMessage();
29. MimeMessageHelper helper = new  MimeMessageHelper(msg,  true ,  "utf-8" );
30. String toList = getMailList(address);
31. InternetAddress\[] iaToList = new  InternetAddress().parse(toList);
32. msg.setRecipients(Message.RecipientType.TO,iaToList);
33. helper.setFrom(from);
34. helper.setSubject(subject);
35. helper.setText(content, true );
36. //添加内嵌文件，第1个参数为cid标识这个文件,第2个参数为资源
37. helper.addInline("a" ,  new  File( "E:/logo\_a.jpg" ));  //附件内容
38. helper.addInline("b" ,  new  File( "E:/logo\_b.png" ));
39. File file=new  File( "E:/测试中文文件.rar" );
40. // 这里的方法调用和插入图片是不同的，使用MimeUtility.encodeWord()来解决附件名称的中文问题
41. helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
42. //如果主题出现乱码，可以使用该函数，也可以使用下面的函数
43. //helper.setSubject(MimeUtility.encodeText(String text,String charset,String encoding))
44. //第2个参数表示字符集，第三个为目标编码格式。
45. //MimeUtility.encodeWord(String word,String charset,String encoding)
46. sender.send(msg);
47. }
48. /\**
49. * 集合转换字符串
50. \*/
51. public  String getMailList(List&lt;String&gt; to){
52. StringBuffer toList = new  StringBuffer();
53. int  length = to.size();
54. if (to!= null  && length &lt; 2 ){
55. toList.append(to.get(0 ));
56. }else {
57. for ( int  i= 0 ;i&lt;length;i++){
58. toList.append(to.get(i));
59. if (i!=(length- 1 )){
60. toList.append("," );
61. }
62. }
63. }
64. return  toList.toString();
65. }
66. //通过模板构造邮件内容，参数content将替换模板文件中的${content}标签。
67. private  String getMailText(String content)  throws  Exception {
68. String htmlText = "" ;
69. //通过指定模板名获取FreeMarker模板实例
70. Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate("registerUser.ftl" );
71. Map map = new  HashMap();     //FreeMarker通过Map传递动态数据
72. map.put("content" ,content);  //注意动态数据的key和模板标签中指定的属性相匹配
73. //解析模板并替换动态数据，最终content将替换模板文件中的${content}标签。
74. htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl,map);
75. return  htmlText;
76. }
77. }