隨筆-126  評論-247  文章-5  trackbacks-0
          前言:說過了 Spring 如何發(fā)送 Email 之后,接著來說一下,怎么樣用 Spring 來發(fā)送帶有附件的郵件,其實實現(xiàn)這個也很簡單,
          Spring 的官方文檔也有給出例子,下面來說下我的實現(xiàn)。

          環(huán)境:
          JDK        1.6
            Spring     2.5.6 
          Javamail  1.4.4 
          Maven     3.0.4 
          Myeclipse 8.6.1

          項目結(jié)構(gòu):


          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  >
            
              
          <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賬號都是網(wǎng)易的,下面列出網(wǎng)易的SMTP服務器名和端口號:
                 網(wǎng)易郵箱          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">
                  
          <!-- 發(fā)件人email -->
                  
          <property name="from" value="fancydeepin@yeah.net" />
                  
          <!-- 
                   收件人email
                  <property name="to" value="to@yeah.net" />
                  email主題(標題)
                  <property name="subject" value="Subject" />
                  email主題內(nèi)容
                  <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
           * @描述: 發(fā)送Email工具類
           * -----------------------------------------
           
          */

          public class Email {
              
              
          private JavaMailSender javaMailSender;
              
          private SimpleMailMessage simpleMailMessage;
              
            
          /**
               * @方法名: sendMail 
               * @參數(shù)名:
          @param subject 郵件主題
               * @參數(shù)名:
          @param content 郵件主題內(nèi)容
               * @參數(shù)名:
          @param to        收件人Email地址
               * @描述語:  發(fā)送郵件
               
          */

              
          public void sendMail(String subject, String content, String to) {
                  
                  
          try {
                      MimeMessage mimeMessage 
          = javaMailSender.createMimeMessage();
                    
          /**
                       * new MimeMessageHelper(mimeMessage,true)之true個人見解:
                       * 關(guān)于true參數(shù),官方文檔是這樣解釋的:
                       * use the true flag to indicate you need a multipart message
                       * 翻譯過來就是:使用true,以表明你需要多個消息
                       * 再去翻一下MimeMessageHelper的API,找到這樣一句話:
                       * supporting alternative texts, inline elements and attachments
                       * 也就是說,如果要支持內(nèi)聯(lián)元素和附件就必須給定第二個參數(shù)為true
                       * 否則拋出 java.lang.IllegalStateException 異常
                       
          */

                      MimeMessageHelper messageHelper 
          = new MimeMessageHelper(mimeMessage,true);
                      messageHelper.setFrom(simpleMailMessage.getFrom()); 
          //設置發(fā)件人Email
                      messageHelper.setSubject(subject); //設置郵件主題
                      messageHelper.setText(content);   //設置郵件主題內(nèi)容
                      messageHelper.setTo(to);          //設定收件人Email
                    /**
                       * ClassPathResource:很明顯就是類路徑資源,我這里的附件是在項目里的,所以需要用ClassPathResource
                       * 如果是系統(tǒng)文件資源就不能用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都實現(xiàn)了這個接口
                       
          */

                      messageHelper.addAttachment(file.getFilename(), file); 
          //添加附件
                      javaMailSender.send(mimeMessage);    //發(fā)送附件郵件
                      
                  }
           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測試,運行將發(fā)送一封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("標題", "內(nèi)容", "收件人郵箱");
              }

          }

          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 收到郵件:











          測試完成,英文、中文、壓縮包 附件都能正常發(fā)送和下載。


          下面附上 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 閱讀(4987) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 望谟县| 开化县| 张家界市| 伊春市| 沾化县| 延安市| 华蓥市| 巴林右旗| 黑山县| 绥阳县| 绥化市| 北碚区| 元氏县| 芷江| 杭州市| 长宁区| 宜兴市| 阜南县| 阿荣旗| 通化市| 江城| 科尔| 海南省| 宁阳县| 土默特右旗| 吕梁市| 汉阴县| 怀宁县| 玉树县| 安化县| 白城市| 合阳县| 金秀| 兴宁市| 兴城市| 拉孜县| 石家庄市| 三门峡市| 乐业县| 理塘县| 梓潼县|