随笔-126  评论-247  文章-5  trackbacks-0
前言:说过了 Spring 如何发送 Email 之后,接着来说一下,怎么样用 Spring 来发送带有附件的邮件,其实实现这个也很简单,
Spring 的官方文档也有给出例子,下面来说下我的实现。

环境:
JDK        1.6
  Spring     2.5.6 
Javamail  1.4.4 
Maven     3.0.4 
Myeclipse 8.6.1

项目结构:


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

Email.java
package com.fancy.util;

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

public class Email {
    
    
private JavaMailSender javaMailSender;
    
private SimpleMailMessage simpleMailMessage;
    
  
/**
     * @方法名: sendMail 
     * @参数名:
@param subject 邮件主题
     * @参数名:
@param content 邮件主题内容
     * @参数名:
@param to        收件人Email地址
     * @描述语:  发送邮件
     
*/

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

            MimeMessageHelper messageHelper 
= new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(simpleMailMessage.getFrom()); 
//设置发件人Email
            messageHelper.setSubject(subject); //设置邮件主题
            messageHelper.setText(content);   //设置邮件主题内容
            messageHelper.setTo(to);          //设定收件人Email
          /**
             * ClassPathResource:很明显就是类路径资源,我这里的附件是在项目里的,所以需要用ClassPathResource
             * 如果是系统文件资源就不能用ClassPathResource,而要用FileSystemResource,例:
             * FileSystemResource file = new FileSystemResource(new File("D:/Readme.txt"));
             
*/

            ClassPathResource file 
= new ClassPathResource("attachment/Readme.txt");
          
/**
             * MimeMessageHelper的addAttachment方法:
             * addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)
             * InputStreamSource是一个接口,ClassPathResource和FileSystemResource都实现了这个接口
             
*/

            messageHelper.addAttachment(file.getFilename(), file); 
//添加附件
            javaMailSender.send(mimeMessage);    //发送附件邮件
            
        }
 catch (Exception e) {System.out.println("异常信息:" + e);}
    }

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

     
//Spring 依赖注入
    public void setJavaMailSender(JavaMailSender javaMailSender) {
        
this.javaMailSender = javaMailSender;
    }

}


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

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

public class EmailTest extends TestCase {

    
public void testSendMail() {
        ApplicationContext context 
= new ClassPathXmlApplicationContext("spring-smtp-mail-attachment.xml");
        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("标题", "内容", "收件人邮箱");
    }


}

pom.xml
<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">
  
<modelVersion>4.0.0</modelVersion>
  
<groupId>com.fancy</groupId>
  
<artifactId>spring-mail-attachment-example</artifactId>
  
<version>1.0</version>
  
<packaging>jar</packaging>
  
<name>spring-mail-attachment-example</name>
  
<url>http://maven.apache.org</url>
  
<properties>
    
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  
</properties>

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

运行一下 Junit 的 EmailTest.java 收到邮件:











测试完成,英文、中文、压缩包 附件都能正常发送和下载。


下面附上 Spring 官方文档对Attachment的示例:

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();
sender.setHost(
"mail.host.com");

MimeMessage message 
= sender.createMimeMessage();

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

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

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

sender.send(message);



 



  
posted on 2012-06-12 00:29 fancydeepin 阅读(4969) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: