---
title: "利用Spring发送邮件"
author: "duyunfengsolo"
date: "2009-08-21T15:34:25Z"
tags: ["Bean", "IOC", "Spring", "XML", "算法"]
slug: "spring"
draft: false
lastmod: "2009-08-21T15:34:25Z"
id: 454521
url: "https://solodu.iteye.com/blog/454521"
---

本文主要介绍如何使用简单的Spring邮件抽象层来实现邮件发送功能，对于JavaMail中的API并不做介绍。通过对比JavaMail的 API和Spring的邮件抽象层，我觉得，Spring的邮件抽象层优点就是简化了代码量，并能充分利用IOC功能；缺点就是要使用部分Spring API，使程序与第三方框架耦合。关于这方面的内容，可以参考Spring的参考手册。

闲言少叙，现在就说说Spring邮件抽象层。这里将要用的接口和类有：

1 ） MailSender ，它是发送邮件的主要接口，代码如下：

 

Java代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/156851 "复制代码")

01. **public** **interface** MailSender { /\*\** Send the given simple mail message.
02. * @param simpleMessage the message to send
03. * @throws org.springframework.mail.MailParseException
04. * in case of failure when parsing the message
05. * @throws org.springframework.mail.MailAuthenticationException
06. * in case of authentication failure
07. * @throws org.springframework.mail.MailSendException
08. * in case of failure when sending the message
09. \*/
10. **void** send(SimpleMailMessage simpleMessage) **throws** MailException;
11. /\**
12. * Send the given array of simple mail messages in batch.
13. * @param simpleMessages the messages to send
14. * @throws org.springframework.mail.MailParseException
15. * in case of failure when parsing a message
16. * @throws org.springframework.mail.MailAuthenticationException
17. * in case of authentication failure
18. * @throws org.springframework.mail.MailSendException
19. * in case of failure when sending a message
20. \*/
21. **void** send(SimpleMailMessage\[] simpleMessages) **throws** MailException;
22. }

```
public interface MailSender { /*** Send the given simple mail message.

* @param simpleMessage the message to send

* @throws org.springframework.mail.MailParseException

* in case of failure when parsing the message

* @throws org.springframework.mail.MailAuthenticationException

* in case of authentication failure

* @throws org.springframework.mail.MailSendException

* in case of failure when sending the message

*/

void send(SimpleMailMessage simpleMessage) throws MailException;

/**

* Send the given array of simple mail messages in batch.

* @param simpleMessages the messages to send

* @throws org.springframework.mail.MailParseException

* in case of failure when parsing a message

* @throws org.springframework.mail.MailAuthenticationException

* in case of authentication failure

* @throws org.springframework.mail.MailSendException

* in case of failure when sending a message

*/

void send(SimpleMailMessage[] simpleMessages) throws MailException;

}
```

 

2 ）一个简单邮件信息的实现类 SimpleMailMessage 。

3 ） JavaMailSender 接口，提供使用 JavaMail 中 MimeMessage ，代码如下：

Java代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/156851 "复制代码")

01. **public** **interface** MailSender { /\*\** Send the given simple mail message.
02. * @param simpleMessage the message to send
03. * @throws org.springframework.mail.MailParseException
04. * in case of failure when parsing the message
05. * @throws org.springframework.mail.MailAuthenticationException
06. * in case of authentication failure
07. * @throws org.springframework.mail.MailSendException
08. * in case of failure when sending the message
09. \*/
10. **void** send(SimpleMailMessage simpleMessage) **throws** MailException;
11. /\**
12. * Send the given array of simple mail messages in batch.
13. * @param simpleMessages the messages to send
14. * @throws org.springframework.mail.MailParseException
15. * in case of failure when parsing a message
16. * @throws org.springframework.mail.MailAuthenticationException
17. * in case of authentication failure
18. * @throws org.springframework.mail.MailSendException
19. * in case of failure when sending a message
20. \*/
21. **void** send(SimpleMailMessage\[] simpleMessages) **throws** MailException;
22. }

```
public interface MailSender { /*** Send the given simple mail message.

* @param simpleMessage the message to send

* @throws org.springframework.mail.MailParseException

* in case of failure when parsing the message

* @throws org.springframework.mail.MailAuthenticationException

* in case of authentication failure

* @throws org.springframework.mail.MailSendException

* in case of failure when sending the message

*/

void send(SimpleMailMessage simpleMessage) throws MailException;

/**

* Send the given array of simple mail messages in batch.

* @param simpleMessages the messages to send

* @throws org.springframework.mail.MailParseException

* in case of failure when parsing a message

* @throws org.springframework.mail.MailAuthenticationException

* in case of authentication failure

* @throws org.springframework.mail.MailSendException

* in case of failure when sending a message

*/

void send(SimpleMailMessage[] simpleMessages) throws MailException;

}
```

 

使用 JavaMail ，需要依赖 mail.jar 和 activation.jar 两个包。利用 Spring 的 IOC 优势，可以通过配置文件来配置邮件发送信息。对于 MailSender ， Spring 提供了实现类 JavaMailSenderImpl ，可以如下配置 MailSender 信息。 

Xml代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/156851 "复制代码")

1. **&lt;** **bean** id = "mailSender" class = "org.springframework.mail.javamail.JavaMailSenderImpl"**&gt;**
2. **&lt;** **property** name = "host" value = "smtp.126.com"**&gt;**
3. **&lt;** **property** name = "javaMailProperties" **&gt;**
4. **&lt;** **props** **&gt;**
5. **&lt;** **prop** key = "mail.smtp.auth" **&gt;** true
6. **&lt;** **prop** key = "mail.smtp.timeout" **&gt;** 20000
7. **&lt;** **property** name = "username" value = "kafka0102"**&gt;**
8. **&lt;** **property** name = "password" value = "\*\*\*\*"**&gt;**

```
< bean id = "mailSender" class = "org.springframework.mail.javamail.JavaMailSenderImpl"> 

< property name = "host" value = "smtp.126.com">

< property name = "javaMailProperties" >

< props >

< prop key = "mail.smtp.auth" > true

< prop key = "mail.smtp.timeout" > 20000

< property name = "username" value = "kafka0102">

< property name = "password" value = "****">
```

 

可以想到，如果是在 Service 中调用 mailSender ，可以通过 IOC 将 mailSender 注入到 Service 中。这里给出一个简单的使用演示：

 

Java代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/156851 "复制代码")

1. BeanFactory bf = **new** ClassPathXmlApplicationContext( "service-applicationContext.xml" );
2. MailSender ms = (MailSender)bf.getBean( "mailSender" );
3. SimpleMailMessage smm = **new** SimpleMailMessage();
4. smm.setTo( "kafka0102@126.com" );
5. smm.setFrom( "kafka0102@126.com" );
6. smm.setSubject( "hello" );
7. smm.setText( "I am you" );
8. ms.send(smm);

```
BeanFactory bf = new ClassPathXmlApplicationContext( "service-applicationContext.xml" );

MailSender ms = (MailSender)bf.getBean( "mailSender" );

SimpleMailMessage smm = new SimpleMailMessage();

smm.setTo( "kafka0102@126.com" );

smm.setFrom( "kafka0102@126.com" );

smm.setSubject( "hello" );

smm.setText( "I am you" );

ms.send(smm);
```

 

其中， SimpleMailMessage 也可以通过配置文件配置使用到的属性。 SimpleMailMessage 不能发送带有附件的邮件，这时就需要 JavaMailSender （它的实现类也是 JavaMailSenderImpl ）， MimeMessagePreparator 的实现类和部分 JavaMail API 。 mailSender 的配置不变，添加一个实现 MimeMessagePreparator 的类 OneMimeMessagePreparator ，代码如下。

Java代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/156851 "复制代码")

01. **import** java.util.Date; **import** javax.activation.DataHandler;
02. **import** javax.activation.FileDataSource;
03. **import** javax.mail.Message;
04. **import** javax.mail.Multipart;
05. **import** javax.mail.internet.InternetAddress;
06. **import** javax.mail.internet.MimeBodyPart;
07. **import** javax.mail.internet.MimeMessage;
08. **import** javax.mail.internet.MimeMultipart;
09. **import** org.springframework.mail.javamail.MimeMessagePreparator;
10. **public** **class** OneMimeMessagePreparator **implements** MimeMessagePreparator{
11. **public** **void** prepare(MimeMessage mm) **throws** Exception {
12. mm.setRecipient(Message.RecipientType. TO , **new** InternetAddress( "kafka0102@126.com" ));
13. mm.setFrom( **new** InternetAddress( "kafka0102@126.com" ));
14. mm.setSubject( "I am you" );
15. Multipart mp = **new** MimeMultipart();
16. MimeBodyPart mbp = **new** MimeBodyPart();
17. mbp.setText( "hello kafka0102" );
18. mp.addBodyPart(mbp);
19. String\[] files = **new** String\[]{
20. "/home/kafka0102/Document/ 常用基础算法 .txt" ,
21. "/home/kafka0102/Document/21164.html" };
22. **for** (String f : files){
23. MimeBodyPart mbpFile = **new** MimeBodyPart();
24. FileDataSource fds = **new** FileDataSource(f);
25. mbpFile.setDataHandler( **new** DataHandler(fds));
26. mbpFile.setFileName(fds.getName());
27. mp.addBodyPart(mbpFile);
28. }
29. mm.setContent(mp);
30. mm.setSentDate( **new** Date());
31. }
32. }

```
import java.util.Date; import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.Message;

import javax.mail.Multipart;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

import org.springframework.mail.javamail.MimeMessagePreparator;

public class OneMimeMessagePreparator implements MimeMessagePreparator{

public void prepare(MimeMessage mm) throws Exception {

mm.setRecipient(Message.RecipientType. TO , new InternetAddress( "kafka0102@126.com" ));

mm.setFrom( new InternetAddress( "kafka0102@126.com" ));

mm.setSubject( "I am you" );

Multipart mp = new MimeMultipart();

MimeBodyPart mbp = new MimeBodyPart();

mbp.setText( "hello kafka0102" );

mp.addBodyPart(mbp);

String[] files = new String[]{
"/home/kafka0102/Document/ 常用基础算法 .txt" ,
 "/home/kafka0102/Document/21164.html" };

for (String f : files){

MimeBodyPart mbpFile = new MimeBodyPart();

FileDataSource fds = new FileDataSource(f);

mbpFile.setDataHandler( new DataHandler(fds));

mbpFile.setFileName(fds.getName());

mp.addBodyPart(mbpFile);

}

mm.setContent(mp);

mm.setSentDate( new Date());

}

}
```

 

OneMimeMessagePreparator 的功能就是配置 MimeMessage ，其中添加了两个附件。下面就是简单的使用方法。

 

Java代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/156851 "复制代码")

1. BeanFactory bf = **new** ClassPathXmlApplicationContext("service-applicationContext.xml");
2. JavaMailSender ms = (JavaMailSender)bf.getBean("mailSender");
3. ms.send(**new** OneMimeMessagePreparator());

```
BeanFactory bf = new ClassPathXmlApplicationContext("service-applicationContext.xml");

JavaMailSender ms = (JavaMailSender)bf.getBean("mailSender");

ms.send(new OneMimeMessagePreparator());

```