前言:说过了 Spring 如何发送 Email 之后,接着来说一下,怎么样用 Spring 来发送带有附件的邮件,其实实现这个也很简单,
Spring 的官方文档也有给出例子,下面来说下我的实现。
环境:
项目结构:

spring-smtp-mail-attachment.xml
 <beans xmlns=http://www.springframework.org/schema/beans  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<beans xmlns=http://www.springframework.org/schema/beans  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
  
 <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
 <!-- 服务器 -->
        <!-- 服务器 -->
 <property name="host" value="smtp.yeah.net" />
        <property name="host" value="smtp.yeah.net" />
 <!-- 端口号 -->
        <!-- 端口号 -->
 <property name="port" value="25" />
        <property name="port" value="25" />
 <!-- 用户名 -->
        <!-- 用户名 -->
 <property name="username" value="fancydeepin@yeah.net" />
        <property name="username" value="fancydeepin@yeah.net" />
 <!--  密码   -->
        <!--  密码   -->
 <property name="password" value="*********" />
        <property name="password" value="*********" />
 <!-- SMTP服务器验证 -->
        <!-- SMTP服务器验证 -->
 <property name="javaMailProperties">
        <property name="javaMailProperties">
 <props>
            <props>
 <!-- 验证身份 -->
               <!-- 验证身份 -->
 <prop key="mail.smtp.auth">true</prop>
               <prop key="mail.smtp.auth">true</prop>
 </props>
            </props>
 </property>
        </property>
 </bean>
    </bean>
 <!--
    <!-- 
 目前我用过的EMAIL账号都是网易的,下面列出网易的SMTP服务器名和端口号:
       目前我用过的EMAIL账号都是网易的,下面列出网易的SMTP服务器名和端口号:
 网易邮箱          SMTP服务器     SMTP端口    POP3服务器      POP3端口
       网易邮箱          SMTP服务器     SMTP端口    POP3服务器      POP3端口
 @126.com     smtp.126.com      25         pop3.126.com      110
       @126.com     smtp.126.com      25         pop3.126.com      110
 @163.com     smtp.163.com      25         pop3.163.com      110
       @163.com     smtp.163.com      25         pop3.163.com      110
 @yeah.net    smtp.yeah.net      25         pop3.yeah.net     110
       @yeah.net    smtp.yeah.net      25         pop3.yeah.net     110
 -->
    -->
 
    
 <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
    <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
 <!-- 发件人email -->
        <!-- 发件人email -->
 <property name="from" value="fancydeepin@yeah.net" />
        <property name="from" value="fancydeepin@yeah.net" />
 <!--
        <!-- 
 收件人email
         收件人email
 <property name="to" value="to@yeah.net" />
        <property name="to" value="to@yeah.net" />
 email主题(标题)
        email主题(标题)
 <property name="subject" value="Subject" />
        <property name="subject" value="Subject" />
 email主题内容
        email主题内容
 <property name="text">
        <property name="text">
 <value>ContentText</value>
          <value>ContentText</value>
 </property>
        </property>
 -->
        -->
 </bean>
    </bean>
 
    
 <bean id="simpleMail" class="com.fancy.util.Email">
    <bean id="simpleMail" class="com.fancy.util.Email">
 <property name="javaMailSender" ref="javaMailSender" />
        <property name="javaMailSender" ref="javaMailSender" />
 <property name="simpleMailMessage" ref="simpleMailMessage" />
        <property name="simpleMailMessage" ref="simpleMailMessage" />
 </bean>
    </bean>
 
    
 </beans>
</beans> 
Email.java
 package com.fancy.util;
package com.fancy.util;

 import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage;
 import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ClassPathResource;
 import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.SimpleMailMessage;
 import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSender;
 import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessageHelper;
 /**
/**
 * -----------------------------------------
 * -----------------------------------------
 * @文件: Email.java
 * @文件: Email.java
 * @作者: fancy
 * @作者: fancy
 * @邮箱: fancydeepin@yeah.net
 * @邮箱: fancydeepin@yeah.net
 * @时间: 2012-6-12
 * @时间: 2012-6-12
 * @描述: 发送Email工具类
 * @描述: 发送Email工具类
 * -----------------------------------------
 * -----------------------------------------
 */
 */

 public class Email {
public class Email {
 
    
 private JavaMailSender javaMailSender;
    private JavaMailSender javaMailSender;
 private SimpleMailMessage simpleMailMessage;
    private SimpleMailMessage simpleMailMessage;
 
    

 /**
  /**
 * @方法名: sendMail
     * @方法名: sendMail 
 * @参数名:@param subject 邮件主题
     * @参数名:@param subject 邮件主题
 * @参数名:@param content 邮件主题内容
     * @参数名:@param content 邮件主题内容
 * @参数名:@param to        收件人Email地址
     * @参数名:@param to        收件人Email地址
 * @描述语:  发送邮件
     * @描述语:  发送邮件
 */
     */

 public void sendMail(String subject, String content, String to) {
    public void sendMail(String subject, String content, String to) {
 
        

 try {
        try {
 MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();

 /**
          /**
 * new MimeMessageHelper(mimeMessage,true)之true个人见解:
             * new MimeMessageHelper(mimeMessage,true)之true个人见解:
 * 关于true参数,官方文档是这样解释的:
             * 关于true参数,官方文档是这样解释的:
 * use the true flag to indicate you need a multipart message
             * use the true flag to indicate you need a multipart message
 * 翻译过来就是:使用true,以表明你需要多个消息
             * 翻译过来就是:使用true,以表明你需要多个消息
 * 再去翻一下MimeMessageHelper的API,找到这样一句话:
             * 再去翻一下MimeMessageHelper的API,找到这样一句话:
 * supporting alternative texts, inline elements and attachments
             * supporting alternative texts, inline elements and attachments
 * 也就是说,如果要支持内联元素和附件就必须给定第二个参数为true
             * 也就是说,如果要支持内联元素和附件就必须给定第二个参数为true
 * 否则抛出 java.lang.IllegalStateException 异常
             * 否则抛出 java.lang.IllegalStateException 异常
 */
             */
 MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
 messageHelper.setFrom(simpleMailMessage.getFrom()); //设置发件人Email
            messageHelper.setFrom(simpleMailMessage.getFrom()); //设置发件人Email
 messageHelper.setSubject(subject); //设置邮件主题
            messageHelper.setSubject(subject); //设置邮件主题
 messageHelper.setText(content);   //设置邮件主题内容
            messageHelper.setText(content);   //设置邮件主题内容
 messageHelper.setTo(to);          //设定收件人Email
            messageHelper.setTo(to);          //设定收件人Email

 /**
          /**
 * ClassPathResource:很明显就是类路径资源,我这里的附件是在项目里的,所以需要用ClassPathResource
             * ClassPathResource:很明显就是类路径资源,我这里的附件是在项目里的,所以需要用ClassPathResource
 * 如果是系统文件资源就不能用ClassPathResource,而要用FileSystemResource,例:
             * 如果是系统文件资源就不能用ClassPathResource,而要用FileSystemResource,例:
 * FileSystemResource file = new FileSystemResource(new File("D:/Readme.txt"));
             * FileSystemResource file = new FileSystemResource(new File("D:/Readme.txt"));
 */
             */
 ClassPathResource file = new ClassPathResource("attachment/Readme.txt");
            ClassPathResource file = new ClassPathResource("attachment/Readme.txt");

 /**
          /**
 * MimeMessageHelper的addAttachment方法:
             * MimeMessageHelper的addAttachment方法:
 * addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)
             * addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)
 * InputStreamSource是一个接口,ClassPathResource和FileSystemResource都实现了这个接口
             * InputStreamSource是一个接口,ClassPathResource和FileSystemResource都实现了这个接口
 */
             */
 messageHelper.addAttachment(file.getFilename(), file); //添加附件
            messageHelper.addAttachment(file.getFilename(), file); //添加附件
 javaMailSender.send(mimeMessage);    //发送附件邮件
            javaMailSender.send(mimeMessage);    //发送附件邮件
 
            

 } catch (Exception e) {System.out.println("异常信息:" + e);}
        } catch (Exception e) {System.out.println("异常信息:" + e);}
 }
    }
 //Spring 依赖注入
      //Spring 依赖注入

 public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
 this.simpleMailMessage = simpleMailMessage;
        this.simpleMailMessage = simpleMailMessage;
 }
    }
 //Spring 依赖注入
      //Spring 依赖注入

 public void setJavaMailSender(JavaMailSender javaMailSender) {
    public void setJavaMailSender(JavaMailSender javaMailSender) {
 this.javaMailSender = javaMailSender;
        this.javaMailSender = javaMailSender;
 }
    }
 }
}

 
Junit Test:EmailTest.java
 package com.fancy.test;
package com.fancy.test;

 import junit.framework.TestCase;
import junit.framework.TestCase;
 import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 import com.fancy.util.Email;
import com.fancy.util.Email;
 /**
/**
 * -----------------------------------------
 * -----------------------------------------
 * @文件: EmailTest.java
 * @文件: EmailTest.java
 * @作者: fancy
 * @作者: fancy
 * @邮箱: fancydeepin@yeah.net
 * @邮箱: fancydeepin@yeah.net
 * @时间: 2012-6-12
 * @时间: 2012-6-12
 * @描述: Junit测试,运行将发送一封email
 * @描述: Junit测试,运行将发送一封email
 * -----------------------------------------
 * -----------------------------------------
 */
 */

 public class EmailTest extends TestCase {
public class EmailTest extends TestCase {


 public void testSendMail() {
    public void testSendMail() {
 ApplicationContext context = new ClassPathXmlApplicationContext("spring-smtp-mail-attachment.xml");
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-smtp-mail-attachment.xml");
 Email mail = (Email)context.getBean("simpleMail");
        Email mail = (Email)context.getBean("simpleMail");
 mail.sendMail("Spring SMTP Mail With Attachment Subject", "Spring SMTP Mail With Attachment Text Content", "fancyzero@yeah.net");
        mail.sendMail("Spring SMTP Mail With Attachment Subject", "Spring SMTP Mail With Attachment Text Content", "fancyzero@yeah.net");
 //mail.sendMail("标题", "内容", "收件人邮箱");
        //mail.sendMail("标题", "内容", "收件人邮箱");
 }
    }

 }
} 
pom.xml
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
  <modelVersion>4.0.0</modelVersion>
 <groupId>com.fancy</groupId>
  <groupId>com.fancy</groupId>
 <artifactId>spring-mail-attachment-example</artifactId>
  <artifactId>spring-mail-attachment-example</artifactId>
 <version>1.0</version>
  <version>1.0</version>
 <packaging>jar</packaging>
  <packaging>jar</packaging>
 <name>spring-mail-attachment-example</name>
  <name>spring-mail-attachment-example</name>
 <url>http://maven.apache.org</url>
  <url>http://maven.apache.org</url>
 <properties>
  <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
  </properties>

 <dependencies>
  <dependencies>
 <!-- Spring framework -->
    <!-- Spring framework -->
 <dependency>
    <dependency>
 <groupId>org.springframework</groupId>
      <groupId>org.springframework</groupId>
 <artifactId>spring</artifactId>
      <artifactId>spring</artifactId>
 <version>2.5.6</version>
      <version>2.5.6</version>
 </dependency>
    </dependency>
 <!-- Javamail API -->
    <!-- Javamail API -->
 <dependency>
    <dependency>
 <groupId>javax.mail</groupId>
      <groupId>javax.mail</groupId>
 <artifactId>mail</artifactId>
      <artifactId>mail</artifactId>
 <version>1.4.4</version>
      <version>1.4.4</version>
 </dependency>
    </dependency>
 <!-- Junit -->
    <!-- Junit -->
 <dependency>
    <dependency>
 <groupId>junit</groupId>
      <groupId>junit</groupId>
 <artifactId>junit</artifactId>
      <artifactId>junit</artifactId>
 <version>4.1</version>
      <version>4.1</version>
 <scope>test</scope>
      <scope>test</scope>
 </dependency>
    </dependency>
 </dependencies>
  </dependencies>
 
  
 </project>
</project>

 
24.3.1.1 Attachments
The following example shows you how to use the MimeMessageHelper to send an email along with a single JPEG image attachment.
 JavaMailSenderImpl sender = new JavaMailSenderImpl();
JavaMailSenderImpl sender = new JavaMailSenderImpl();
 sender.setHost("mail.host.com");
sender.setHost("mail.host.com");

 MimeMessage message = sender.createMimeMessage();
MimeMessage message = sender.createMimeMessage();

 // use the true flag to indicate you need a multipart message
// use the true flag to indicate you need a multipart message
 MimeMessageHelper helper = new MimeMessageHelper(message, true);
MimeMessageHelper helper = new MimeMessageHelper(message, true);
 helper.setTo("test@host.com");
helper.setTo("test@host.com");

 helper.setText("Check out this image!");
helper.setText("Check out this image!");

 // let's attach the infamous windows Sample file (this time copied to c:/)
// let's attach the infamous windows Sample file (this time copied to c:/)
 FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg"));
FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg"));
 helper.addAttachment("CoolImage.jpg", file);
helper.addAttachment("CoolImage.jpg", file);

 sender.send(message);
sender.send(message);
 
     
	posted on 2012-06-12 00:29 
fancydeepin 阅读(4996) 
评论(0)  编辑  收藏