午后星期午

          Spring郵件服務之附件:Maven + Spring SMTP Mail With Attachment

          前言:說過了 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);



             [ 轉載出處:http://www.aygfsteel.com/fancydeepin ]

          posted on 2013-12-31 13:52 午后星期午 閱讀(277) 評論(0)  編輯  收藏 所屬分類: JavaEE

          主站蜘蛛池模板: 叙永县| 正蓝旗| 江城| 琼海市| 博乐市| 衡阳市| 临沂市| 城市| 南通市| 韶关市| 垫江县| 尼木县| 峨眉山市| 盖州市| 花莲市| 沁源县| 盘锦市| 突泉县| 台中县| 马尔康县| 昌宁县| 宣汉县| 河南省| 托克托县| 丰宁| 济源市| 大埔区| 儋州市| 朔州市| 临沧市| 长兴县| 三门峡市| 鸡泽县| 谷城县| 石阡县| 连山| 葫芦岛市| 溧水县| 舒兰市| 铜山县| 巴林左旗|