posts - 297,  comments - 1618,  trackbacks - 0
               做了個spring發送純文本文件以及發送帶附件的郵件的例子,共享之。
                1. SpringMail類
               
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.FileSystemXmlApplicationContext;
          import org.springframework.mail.SimpleMailMessage;
          import org.springframework.mail.javamail.JavaMailSender;
          import org.springframework.mail.javamail.MimeMessagePreparator;

          import javax.mail.internet.MimeMessage;
          import javax.mail.MessagingException;
          import javax.mail.Message;
          import javax.mail.internet.InternetAddress;
          import javax.activation.FileDataSource;
          import javax.activation.DataHandler;
          import javax.mail.internet.MimeMultipart;
          import javax.mail.internet.MimeBodyPart;
          import javax.mail.Multipart;

          import java.util.List;
          import java.util.ArrayList;
          import java.util.Date;
          import java.util.Iterator;

          /**
           * spring的郵件發送例子
           * 
          @author Amigo Xie(xiexingxing1121@126.com)
           * 
          @since 2007/04/28 11:30
           
          */

          public class SpringMail {

              
          public static void main(String[] args) throws Exception {
                  ApplicationContext ctx 
          = new FileSystemXmlApplicationContext(
                          
          "src/applicationContext.xml");
                  JavaMailSender sender 
          = (JavaMailSender) ctx.getBean("mailSender");
                  SpringMail springMail 
          = new SpringMail();
                  
                  
          //測試發送只有文本信息的簡單測試
                  springMail.sendTextMail(sender);
                  
                  
          //測試發送帶附件的郵件
                  springMail.sendMimeMessage(sender);
              }

              
              
          /**
               * 測試發送只有文本信息的簡單測試
               * 
          @param sender 郵件發送器
               * 
          @throws Exception
               
          */

              
          private void sendTextMail(JavaMailSender sender) throws Exception {
                  SimpleMailMessage mail 
          = new SimpleMailMessage();
                  mail.setTo(
          "xiexingxing1121@126.com");
                  mail.setFrom(
          "xiexingxing1121@126.com");
                  mail.setSubject(
          "test by amigo");
                  mail.setText(
          "spring Mail的簡單測試");
                  sender.send(mail);
                  
                  System.out.println(
          "成功發送文本文件!");
              }

              
              
          /**
               * 發送帶附件的郵件
               * 
          @param sender 郵件發送器 
               * 
          @throws Exception
               
          */

              
          private void sendMimeMessage(final JavaMailSender sender) throws Exception {
                  
          //附件文件集合
                  final List files = new ArrayList();
                  MimeMessagePreparator mimeMail 
          = new MimeMessagePreparator() {
                      
          public void prepare(MimeMessage mimeMessage) throws MessagingException {
                          mimeMessage.setRecipient(Message.RecipientType.TO, 
                                  
          new InternetAddress("xiexingxing1121@126.com"));
                          mimeMessage.setFrom(
          new InternetAddress("xiexingxing1121@126.com"));
                          mimeMessage.setSubject(
          "Spring發送帶附件的郵件""gb2312"); 
                          
                          Multipart mp 
          = new MimeMultipart();
                          
                          
          //向Multipart添加正文
                          MimeBodyPart content = new MimeBodyPart();
                          content.setText(
          "內含spring郵件發送的例子,請查收!");
                          
                          
          //向MimeMessage添加(Multipart代表正文)
                          mp.addBodyPart(content);
                          files.add(
          "src/SpringMail.java");
                          files.add(
          "src/applicationContext.xml");
                          
                          
          //向Multipart添加附件
                          Iterator it = files.iterator();
                          
          while(it.hasNext()) {
                              MimeBodyPart attachFile 
          = new MimeBodyPart();
                              String filename 
          = it.next().toString();
                              FileDataSource fds 
          = new FileDataSource(filename);
                              attachFile.setDataHandler(
          new DataHandler(fds));
                              attachFile.setFileName(fds.getName());
                              mp.addBodyPart(attachFile);
                          }

                          
                          files.clear();
                          
                          
          //向Multipart添加MimeMessage
                          mimeMessage.setContent(mp);
                          mimeMessage.setSentDate(
          new Date());
                      }

                  }
          ;

                  
          //發送帶附件的郵件
                  sender.send(mimeMail);
                  
                  System.out.println(
          "成功發送帶附件郵件!");
              }

          }


                2. spring的配置文件
               
          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

          <beans>
              
          <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
                  
          <property name="host">
                      
          <value>smtp.126.com</value>
                  
          </property>
                  
          <property name="javaMailProperties">
                      
          <props>
                          
          <prop key="mail.smtp.auth">true</prop>
                          
          <prop key="mail.smtp.timeout">25000</prop>
                      
          </props>
                  
          </property>
                  
          <property name="username">
                      
          <value>xiexingxing1121</value>
                  
          </property>
                  
          <property name="password">
                      
          <value><!-- 此處填寫密碼 --></value>
                  
          </property>
              
          </bean>
          </beans>

              剛才發現一bug,當附件名為中文時,會出現中文亂碼問題,對sendMimeMessage方法進行了部分修改,如下:
             
                         sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                          files.add(
          "src/SpringMail.java");
                          files.add(
          "src/applicationContext.xml");
                          files.add(
          "src/謝星星.xml");
                          
                          
          //向Multipart添加附件
                          Iterator it = files.iterator();
                       
          while (it.hasNext()) {
                              MimeBodyPart attachFile 
          = new MimeBodyPart();
                              String filename 
          = it.next().toString();
                              FileDataSource fds 
          = new FileDataSource(filename);
                              attachFile.setDataHandler(
          new DataHandler(fds));
                              attachFile.setFileName(
          "=?GBK?B?"+enc.encode(fds.getName().getBytes())+"?=");
                              mp.addBodyPart(attachFile);
                          }
          posted on 2007-04-28 13:23 阿蜜果 閱讀(17142) 評論(7)  編輯  收藏 所屬分類: Spring


          FeedBack:
          # re: 使用spring發送郵件例
          2007-04-28 14:07 | 王凌華
          :) 我直接用javamail也寫了一個類似的東西。(ThreadPool實現的壓力測試小工具),這里我有幾問題:
          a.
          但是我用126的mailserver的時候,出現這樣的錯誤:

          javax.mail.MessagingException: Could not connect to SMTP host: smtp.126.com, port: 25
          at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:855)
          at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:156)
          at javax.mail.Service.connect(Service.java:256)
          at javax.mail.Service.connect(Service.java:135)
          at javax.mail.Service.connect(Service.java:87)
          at com.sun.mail.smtp.SMTPTransport.connect(SMTPTransport.java:93)
          at MailSender.run(MailSender.java:172)
          at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
          at java.lang.Thread.run(Unknown Source)


          我用我公司的的兩臺mailserver都可以順暢的發mail。

            回復  更多評論
            
          # re: 使用spring發送郵件例[未登錄]
          2007-04-28 15:03 | ronghai
          看看是不是需要SSl驗證  回復  更多評論
            
          # re: 使用spring發送郵件例
          2007-04-29 12:47 | 王凌華
          據我所知,gmail的發送和接受是需要ssl驗證的.

          所以我剛才花了點時間去看了一下javamail里面ssl里面是怎么寫的.
          這是代碼片段:

          ----------------------------------------------------------------------------------
          prop.put("mail.smtp.starttls.enable", "true");
          prop.put("mail.smtp.socketFactory.fallback", "false");
          // props.put("mail.smtp.debug", "true");
          prop.put("mail.smtp.socketFactory.class",
          "javax.net.ssl.SSLSocketFactory");
          prop.put("mail.smtp.port", "465");
          prop.put("mail.smtp.socketFactory.port", "465");
          prop.put("mail.smtps.auth", needAuth);
          prop.put("mail.transport.protocol", "smtp");
          prop.put("mail.smtp.host", mailServer);
          ----------------------------------------------------------------------------------

          ----------------------------------------------------------------------------------
          SMTPTransport transport = (SMTPTransport) session
          .getTransport("smtps");
          ----------------------------------------------------------------------------------
          我的努力換來的是發送期間的TimeOut, 沒有任何跡象表明代碼哪里有問題.
          ... ... ...

          最后我終于明白這里用到了465 port. 而我在公司內網內,這個port默認情況下是禁用的. :) -真倒霉.  回復  更多評論
            
          # re: 使用spring發送郵件例
          2007-04-29 12:50 | 王凌華
          順便貼出gmail的配置URL. 大家有興趣也可以試試:

          http://mail.google.com/support/bin/answer.py?answer=13287  回復  更多評論
            
          # spring發送內嵌郵件的圖片無法正常顯示的問題
          2007-09-14 08:27 | LG
          import java.io.File;
          import javax.mail.MessagingException;
          import javax.mail.internet.*;
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.FileSystemXmlApplicationContext;
          import org.springframework.core.io.FileSystemResource;
          import org.springframework.mail.MailException;
          import org.springframework.mail.javamail.JavaMailSenderImpl;
          import org.springframework.mail.javamail.MimeMessageHelper;



          public class SpringMail {
          public static void main(String[] args) throws Exception{

          ApplicationContext ctx=new FileSystemXmlApplicationContext("src/applicationContext.xml");

          JavaMailSenderImpl sender = (JavaMailSenderImpl)ctx.getBean("mailSender");


          SpringMail springMail=new SpringMail();

          springMail.sendInit(sender);
          }

          private void sendInit(JavaMailSenderImpl sender) throws MessagingException {

          MimeMessage message = sender.createMimeMessage();
          MimeMessageHelper helper = new MimeMessageHelper(message,true,"GB2312");
          helper.setFrom("dongweiyi1125@sina.com");
          helper.setTo("dongweiyi1125@sina.com");
          helper.setSubject("Test");
          helper.setText("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body><h1><a href='#'>郁悶!"
          + "<img src=\"cid:identifier\"></body></html>", true);

          FileSystemResource res = new FileSystemResource(new File("c:/weiyi.jpg"));
          helper.addInline("identifier", res);


          try {
          sender.send(message);
          } catch (MailException e) {
          e.printStackTrace();
          }
          System.out.println("成功發送內嵌文件");
          }
          }


          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">


          <beans>
          <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
          <property name="host">
          <value>smtp.sina.com</value>
          </property>
          <property name="javaMailProperties">
          <props>
          <prop key="mail.smtp.auth">true</prop>
          <prop key="mail.smtp.timeout">25000</prop>
          </props>
          </property>
          <property name="username">
          <value>dongweiyi1125</value>
          </property>
          <property name="password">
          <value>郵箱密碼</value>
          </property>
          </bean>
          </beans>


          以上代碼給新浪郵箱發送郵件時圖片總不能正常顯示,但是給QQ郵箱發送郵件時卻可以正常顯示,不知什么原因,請大蝦出來幫忙……  回復  更多評論
            
          # re: 使用spring發送郵件例 AuthenticationFailedException
          2008-07-12 08:51 | Jayden
          和上面的代碼一樣 怎么老是報AuthenticationFailedException 異常啊  回復  更多評論
            
          # re: 使用spring發送郵件例
          2009-09-03 12:29 | 小程序員
          謝謝,樓主分享~~  回復  更多評論
            
          <2007年4月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

                生活將我們磨圓,是為了讓我們滾得更遠——“圓”來如此。
                我的作品:
                玩轉Axure RP  (2015年12月出版)
                

                Power Designer系統分析與建模實戰  (2015年7月出版)
                
               Struts2+Hibernate3+Spring2   (2010年5月出版)
               

          留言簿(263)

          隨筆分類

          隨筆檔案

          文章分類

          相冊

          關注blog

          積分與排名

          • 積分 - 2296321
          • 排名 - 3

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 时尚| 兰考县| 休宁县| 哈尔滨市| 江陵县| 高台县| 天镇县| 嘉峪关市| 镇沅| 外汇| 财经| 杂多县| 奇台县| 德令哈市| 进贤县| 侯马市| 黎城县| 滦南县| 宜兰县| 永靖县| 南阳市| 洪泽县| 贺兰县| 宁都县| 葵青区| 广饶县| 曲麻莱县| 星子县| 水富县| 新郑市| 普兰县| 朝阳县| 齐河县| 读书| 东至县| 信阳市| 桃源县| 六枝特区| 白朗县| 昭通市| 富顺县|