---
title: "spring3.0发送电子邮件（velocity模板，带附件，群发，解决乱码"
author: "simgsg"
date: "2011-07-05T18:15:00Z"
tags: []
categories: ["企业架构"]
slug: "spring3-0-velocity"
draft: false
lastmod: "2011-07-10T13:28:10Z"
id: 1120937
url: "https://simgsg.iteye.com/blog/1120937"
---

在这个例子中，将与发送方相关的配置信息放在了一个email.properties文件中，spring容器启动的时候会从这个属性文件中读取发送方的配置信息，这样配置的主要原因在于，发送方一般都是固定不变的。

我将发送的内容放在一个velocity模板文件中，这个文件很像jsp文件，您可以从[http://airport.iteye.com/blog/23634](http://airport.iteye.com/blog/23634)中获取更多的关于velocity使用方法相关的信息。（实际上velocity是Apache提供的一种模板语言）。我希望邮件接收方能够接收一个动态的网页，而不是一个简单的文本。

另外，程序提供了发送附件的部分，和群发的功能，只不过群发功能并不完善，因为群发过程中无法将模板变量替换成用户相关变量值，这是个缺陷，楼主也没想明白如何实现。 

下面将代码贴出，希望对大家有帮助：

先是email.properties文件：

 

 

Java代码 [![复制代码](http://tdcq.iteye.com/images/icon_copy.gif)](http://tdcq.iteye.com/blog/837369 "复制代码") [![收藏代码](http://tdcq.iteye.com/images/icon_star.png)](http://tdcq.iteye.com/blog/837369 "收藏这段代码")

1. email.host=smtp.163.com
2. email.username=woshiguanxinquan
3. email.password=\*\*\*\*\*\*\*\**
4. mail.smtp.auth=true

[view plain](http://blog.csdn.net/shimiso/article/details/6586341 "view plain")

1. email.host=smtp.163.com
2. email.username=woshiguanxinquan
3. email.password=\*\*\*\*\*\*\*\**
4. mail.smtp.auth=true

 模板文件：

 

 

 

Java代码 [![复制代码](http://tdcq.iteye.com/images/icon_copy.gif)](http://tdcq.iteye.com/blog/837369 "复制代码") [![收藏代码](http://tdcq.iteye.com/images/icon_star.png)](http://tdcq.iteye.com/blog/837369 "收藏这段代码")

01. Wecome.vm
02. &lt;html&gt;
03. &lt;body&gt;
04. &lt;h3&gt;您好 $!{userName}, 欢迎您加入编程爱好者俱乐部!&lt;/h3&gt;
05. &lt;div&gt;
06. 您的email地址是&lt;a href="mailto:${emailAddress}"&gt;$!{emailAddress}&lt;/a&gt;.
07. 本条信息是系统自动发送，请勿回复！
08. &lt;/div&gt;
09. &lt;/body&gt;
10. &lt;/html&gt;

[view plain](http://blog.csdn.net/shimiso/article/details/6586341 "view plain")

01. Wecome.vm
02. &lt;html&gt;
03. &lt;body&gt;
04. &lt;h3&gt;您好 $!{userName}, 欢迎您加入编程爱好者俱乐部!&lt;/h3&gt;
05. &lt;div&gt;
06. 您的email地址是&lt;a href="mailto:${emailAddress}"&gt;$!{emailAddress}&lt;/a&gt;.
07. 本条信息是系统自动发送，请勿回复！
08. &lt;/div&gt;
09. &lt;/body&gt;
10. &lt;/html&gt;

 

简单解释一下，很明显这是个html文件，注意$!{[]()[userName]()}实际上是一个变量，在程序运行的时候，由model（一个hashmap类型的变量）传入的值会将其替换，（model的key就是变量的名字，这里是userName，而value就是要替换的值），！表示如果没有替换的值，此处为空。更多详细信息请参考：[http://airport.iteye.com/blog/23634](http://airport.iteye.com/blog/23634)

下面是spring的配置文件：

ThirdVelocityEmailConfig.xml

 

 

Java代码 [![复制代码](http://tdcq.iteye.com/images/icon_copy.gif)](http://tdcq.iteye.com/blog/837369 "复制代码") [![收藏代码](http://tdcq.iteye.com/images/icon_star.png)](http://tdcq.iteye.com/blog/837369 "收藏这段代码")

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:security="http://www.springframework.org/schema/security"
04. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05. xmlns:flex="http://www.springframework.org/schema/flex"
06. xmlns:context="http://www.springframework.org/schema/context"
07. xsi:schemaLocation="
08. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
09. http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
10. http://www.springframework.org/schema/flex
11. http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
12. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt;
13. &lt;context:property-placeholder location="classpath:/com/guan/chapter19/email/email.properties"/&gt;
14. &lt;context:annotation-config/&gt;
15. &lt;context:component-scan base-package="com.guan.chapter19.email"/&gt;
16. &lt;bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean"&gt;
17. &lt;property name="velocityProperties"&gt;
18. &lt;value&gt;
19. resource.loader=class
20. class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
21. &lt;/value&gt;
22. &lt;/property&gt;
23. &lt;/bean&gt;
24. &lt;/beans&gt;

[view plain](http://blog.csdn.net/shimiso/article/details/6586341 "view plain")

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:security="http://www.springframework.org/schema/security"
04. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05. xmlns:flex="http://www.springframework.org/schema/flex"
06. xmlns:context="http://www.springframework.org/schema/context"
07. xsi:schemaLocation="
08. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
09. http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
10. http://www.springframework.org/schema/flex
11. http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
12. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt;
13. &lt;context:property-placeholder location="classpath:/com/guan/chapter19/email/email.properties"/&gt;
14. &lt;context:annotation-config/&gt;
15. &lt;context:component-scan base-package="com.guan.chapter19.email"/&gt;
16. &lt;bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean"&gt;
17. &lt;property name="velocityProperties"&gt;
18. &lt;value&gt;
19. resource.loader=class
20. class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
21. &lt;/value&gt;
22. &lt;/property&gt;
23. &lt;/bean&gt;
24. &lt;/beans&gt;

 

 

这个大家都熟悉，不多解释，开始的时候加载了email.properties文件，我们上面给出了，然后创建了velocityEngine的bean。

下面是spring的配置类：

 

 

Java代码 [![复制代码](http://tdcq.iteye.com/images/icon_copy.gif)](http://tdcq.iteye.com/blog/837369 "复制代码") [![收藏代码](http://tdcq.iteye.com/images/icon_star.png)](http://tdcq.iteye.com/blog/837369 "收藏这段代码")

01. package com.guan.chapter19.email;
02. import java.util.Properties;
03. import org.springframework.beans.factory.annotation.Value;
04. import org.springframework.context.annotation.Bean;
05. import org.springframework.context.annotation.Configuration;
06. import org.springframework.mail.javamail.JavaMailSender;
07. import org.springframework.mail.javamail.JavaMailSenderImpl;
08. @Configuration
09. public class ThirdVelocityEmailAppConfig {
10. //从配置文件中读取相应的邮件配置属性
11. private @Value("${email.host}") String emailHost;
12. private @Value("${email.username}") String userName;
13. private @Value("${email.password}") String password;
14. private @Value("${mail.smtp.auth}") String mailAuth;
15. //JavaMailSender用来发送邮件的类
16. public @Bean JavaMailSender  mailSender(){
17. JavaMailSenderImpl ms = new JavaMailSenderImpl();
18. ms.setHost(emailHost);
19. ms.setUsername(userName);
20. ms.setPassword(password);
21. Properties pp = new Properties();
22. pp.setProperty("mail.smtp.auth", mailAuth);
23. ms.setJavaMailProperties(pp);
24. return ms;
25. }
26. }

[view plain](http://blog.csdn.net/shimiso/article/details/6586341 "view plain")

01. package com.guan.chapter19.email;
02. import java.util.Properties;
03. import org.springframework.beans.factory.annotation.Value;
04. import org.springframework.context.annotation.Bean;
05. import org.springframework.context.annotation.Configuration;
06. import org.springframework.mail.javamail.JavaMailSender;
07. import org.springframework.mail.javamail.JavaMailSenderImpl;
08. @Configuration
09. public class ThirdVelocityEmailAppConfig {
10. //从配置文件中读取相应的邮件配置属性
11. private @Value("${email.host}") String emailHost;
12. private @Value("${email.username}") String userName;
13. private @Value("${email.password}") String password;
14. private @Value("${mail.smtp.auth}") String mailAuth;
15. //JavaMailSender用来发送邮件的类
16. public @Bean JavaMailSender  mailSender(){
17. JavaMailSenderImpl ms = new JavaMailSenderImpl();
18. ms.setHost(emailHost);
19. ms.setUsername(userName);
20. ms.setPassword(password);
21. Properties pp = new Properties();
22. pp.setProperty("mail.smtp.auth", mailAuth);
23. ms.setJavaMailProperties(pp);
24. return ms;
25. }
26. }

 

对于spring是否应该由类来配置，我并不关心，一般情况下，我更倾向于annotation这种形式，因为看起来比xml舒服点，但是annotation不能完全取代xml配置方式（至少现在是这样的），当然您完全可以使用xml进行bean的配置，效果是一样的。在这个配置类中，将从email.properties中读取的值赋值给了JavaMailSenderImpl，这个对象是java邮件发送的主要类，使用其send方法可以将预先准备好的消息发送出去。 

下面给出发送服务的源码

 

 

Java代码 [![复制代码](http://tdcq.iteye.com/images/icon_copy.gif)](http://tdcq.iteye.com/blog/837369 "复制代码") [![收藏代码](http://tdcq.iteye.com/images/icon_star.png)](http://tdcq.iteye.com/blog/837369 "收藏这段代码")

01. package com.guan.chapter19.email;
02. import java.io.File;
03. import java.util.Map;
04. import javax.mail.internet.MimeMessage;
05. import org.apache.velocity.app.VelocityEngine;
06. import org.springframework.beans.factory.annotation.Autowired;
07. import org.springframework.core.io.FileSystemResource;
08. import org.springframework.mail.javamail.JavaMailSender;
09. import org.springframework.mail.javamail.MimeMessageHelper;
10. import org.springframework.mail.javamail.MimeMessagePreparator;
11. import org.springframework.stereotype.Component;
12. import org.springframework.ui.velocity.VelocityEngineUtils;
13. @Component
14. public class ThirdVelocityEmailService {
15. private JavaMailSender  mailSender;
16. private VelocityEngine velocityEngine;
17. @Autowired
18. public void setMailSender(JavaMailSender  mailSender)
19. {
20. this.mailSender = mailSender;
21. }
22. @Autowired
23. public void setVelocityEngine(VelocityEngine velocityEngine)
24. {
25. this.velocityEngine = velocityEngine;
26. }
27. public void sendEmail(final Map&lt;String,Object&gt; model,final String subject,final String vmfile,final String\[] mailTo,final String \[] files)
28. {
29. MimeMessagePreparator preparator = new MimeMessagePreparator() {
30. //注意MimeMessagePreparator接口只有这一个回调函数
31. public void prepare(MimeMessage mimeMessage) throws Exception
32. {
33. MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"GBK");
34. //这是一个生成Mime邮件简单工具，如果不使用GBK这个，中文会出现乱码
35. //如果您使用的都是英文，那么可以使用MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
36. message.setTo(mailTo);//设置接收方的email地址
37. message.setSubject(subject);//设置邮件主题
38. message.setFrom("woshiguanxinquan@163.com");//设置发送方地址
39. String text = VelocityEngineUtils.mergeTemplateIntoString(
40. velocityEngine, vmfile,"GBK", model);
41. //从模板中加载要发送的内容，vmfile就是模板文件的名字
42. //注意模板中有中文要加GBK，model中存放的是要替换模板中字段的值
43. message.setText(text, true);
44. //将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
45. //如果您不想解析文本内容，可以使用false或者不添加这项
46. FileSystemResource file;
47. for(String s:files)//添加附件
48. {
49. file = new FileSystemResource(new File(s));//读取附件
50. message.addAttachment(s, file);//向email中添加附件
51. }
52. }
53. };
54. mailSender.send(preparator);//发送邮件
55. }
56. }

[view plain](http://blog.csdn.net/shimiso/article/details/6586341 "view plain")

01. package com.guan.chapter19.email;
02. import java.io.File;
03. import java.util.Map;
04. import javax.mail.internet.MimeMessage;
05. import org.apache.velocity.app.VelocityEngine;
06. import org.springframework.beans.factory.annotation.Autowired;
07. import org.springframework.core.io.FileSystemResource;
08. import org.springframework.mail.javamail.JavaMailSender;
09. import org.springframework.mail.javamail.MimeMessageHelper;
10. import org.springframework.mail.javamail.MimeMessagePreparator;
11. import org.springframework.stereotype.Component;
12. import org.springframework.ui.velocity.VelocityEngineUtils;
13. @Component
14. public class ThirdVelocityEmailService {
15. private JavaMailSender  mailSender;
16. private VelocityEngine velocityEngine;
17. @Autowired
18. public void setMailSender(JavaMailSender  mailSender)
19. {
20. this.mailSender = mailSender;
21. }
22. @Autowired
23. public void setVelocityEngine(VelocityEngine velocityEngine)
24. {
25. this.velocityEngine = velocityEngine;
26. }
27. public void sendEmail(final Map&lt;String,Object&gt; model,final String subject,final String vmfile,final String\[] mailTo,final String \[] files)
28. {
29. MimeMessagePreparator preparator = new MimeMessagePreparator() {
30. //注意MimeMessagePreparator接口只有这一个回调函数
31. public void prepare(MimeMessage mimeMessage) throws Exception
32. {
33. MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"GBK");
34. //这是一个生成Mime邮件简单工具，如果不使用GBK这个，中文会出现乱码
35. //如果您使用的都是英文，那么可以使用MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
36. message.setTo(mailTo);//设置接收方的email地址
37. message.setSubject(subject);//设置邮件主题
38. message.setFrom("woshiguanxinquan@163.com");//设置发送方地址
39. String text = VelocityEngineUtils.mergeTemplateIntoString(
40. velocityEngine, vmfile,"GBK", model);
41. //从模板中加载要发送的内容，vmfile就是模板文件的名字
42. //注意模板中有中文要加GBK，model中存放的是要替换模板中字段的值
43. message.setText(text, true);
44. //将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
45. //如果您不想解析文本内容，可以使用false或者不添加这项
46. FileSystemResource file;
47. for(String s:files)//添加附件
48. {
49. file = new FileSystemResource(new File(s));//读取附件
50. message.addAttachment(s, file);//向email中添加附件
51. }
52. }
53. };
54. mailSender.send(preparator);//发送邮件
55. }
56. }

 

主要是mailSend这个方法，在这个方法里先创建了一个消息，然后调用mailSender将消息发送出去。 

最后给出测试程序：

 

 

Java代码 [![复制代码](http://tdcq.iteye.com/images/icon_copy.gif)](http://tdcq.iteye.com/blog/837369 "复制代码") [![收藏代码](http://tdcq.iteye.com/images/icon_star.png)](http://tdcq.iteye.com/blog/837369 "收藏这段代码")

01. package com.guan.chapter19.email;
02. import java.util.HashMap;
03. import java.util.Map;
04. import org.junit.Test;
05. import org.springframework.context.ApplicationContext;
06. import org.springframework.context.support.ClassPathXmlApplicationContext;
07. public class ThirdVelocityEmailTest {
08. @Test
09. public void sendEmail()
10. {
11. ApplicationContext context =
12. new ClassPathXmlApplicationContext("com/guan/chapter19/email/ThirdVelocityEmailConfig.xml");
13. ThirdVelocityEmailService tves = context.getBean(ThirdVelocityEmailService.class);
14. Map&lt;String,Object&gt; model = new HashMap&lt;String,Object&gt;();
15. model.put("userName","大关");
16. model.put("emailAddress", "woshidaguan@126.com");
17. tves.sendEmail(model,"欢迎您的加入","com/guan/chapter19/email/welcome.vm",new String\[]{"woshiguanxinquan@163.com"},new String\[]{"F:/Sunset.jpg","F:/spring-hibernate.rar"});
18. //参数说明：替换velocity模板的变量和值对，邮件主题，velocity模板文件的路径，接收方email地址，附件
19. //简单说明，如果您要群发，可以在接收方email地址中多传入几个email地址，附件可以一次发送多个
20. }
21. }

[view plain](http://blog.csdn.net/shimiso/article/details/6586341 "view plain")

01. package com.guan.chapter19.email;
02. import java.util.HashMap;
03. import java.util.Map;
04. import org.junit.Test;
05. import org.springframework.context.ApplicationContext;
06. import org.springframework.context.support.ClassPathXmlApplicationContext;
07. public class ThirdVelocityEmailTest {
08. @Test
09. public void sendEmail()
10. {
11. ApplicationContext context =
12. new ClassPathXmlApplicationContext("com/guan/chapter19/email/ThirdVelocityEmailConfig.xml");
13. ThirdVelocityEmailService tves = context.getBean(ThirdVelocityEmailService.class);
14. Map&lt;String,Object&gt; model = new HashMap&lt;String,Object&gt;();
15. model.put("userName","大关");
16. model.put("emailAddress", "woshidaguan@126.com");
17. tves.sendEmail(model,"欢迎您的加入","com/guan/chapter19/email/welcome.vm",new String\[]{"woshiguanxinquan@163.com"},new String\[]{"F:/Sunset.jpg","F:/spring-hibernate.rar"});
18. //参数说明：替换velocity模板的变量和值对，邮件主题，velocity模板文件的路径，接收方email地址，附件
19. //简单说明，如果您要群发，可以在接收方email地址中多传入几个email地址，附件可以一次发送多个
20. }
21. }

 

 

 

这个程序对一个email来说功能已经很全面了，您可以对其更改然后应用于您的程序中。

 

再次简单说明一下，主机的信息配置在mail.properties文件中，发送的内容写在velocity模板文件中，在执行的时候将相应的字段进行替换。使用了MimeMessagePreparator进行复杂邮件的发送，MimeMessageHelper帮助简化邮件信息过程。解决了中文乱码问题。