姿姿霸霸~~!
          貴在堅持!
          posts - 106,  comments - 50,  trackbacks - 0

          1.用spring的mail發郵件需要將j2ee包里的mail.jar和activation.jar引入
          2.遇見的異常可能會有
             (1)java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
             (2)java.lang.NoClassDefFoundError: com/sun/activation/registries/LogSupport
          這2個異常都是由于JavaEE版本和JavaMail的版本不一致所造成的.如javaMail1.3以下的如果在javaEE5上就會出現上面的錯誤,因為javaEE5中包含有javaMail的類但是卻不全面,所以造成與本身的JavaMail包沖突。而activation1.0.2與1.1版本也不同,LogSupport在1.0.2中沒有。
          3.各個郵件服務器的驗證可能不一定都能通過,多換幾個試試。
          4.發送簡單郵件可以使用SimpleMailMessage
          5.發送帶附件的郵件可以使用MimeMessage+MimeMessageHelper
          6.如果要發送html格式的內容,MimeMessageHelper中的方法setText("需要發送的html格式的內容",true)
          7.如果在容器中使用spring發送郵件的話,在讀取配置文件的時候,因為容器的特殊性,不需要使用 ApplicationContext ctx = new FileSystemXmlApplicationContext( "src/mail-config.xml") ,可以使用ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext())來獲取ctx。在容器初始化的時候將這個ctx獲取之后存在某個靜態變量中去。在使用的時候再根據這個ctx去獲取相應的bean。

          代碼如下:
          1.SendMail類

          import java.io.File;
          import java.io.IOException;
          import java.util.HashMap;
          import java.util.Iterator;
          import java.util.List;
          import java.util.Map;

          import javax.mail.internet.MimeMessage;
          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;

          import org.apache.commons.fileupload.FileItem;
          import org.apache.commons.fileupload.disk.DiskFileItemFactory;
          import org.apache.commons.fileupload.servlet.ServletFileUpload;

          import org.springframework.core.io.FileSystemResource;
          import org.springframework.mail.SimpleMailMessage;
          import org.springframework.mail.javamail.JavaMailSender;
          import org.springframework.mail.javamail.MimeMessageHelper;

          import com.sureframe.BeanManager;

          /**
           * 
          @author zpruan
           * @mail  <xrzp_dh@yahoo.com.cn>
           
          */

          public class SendMail {

              
          // 將郵件頁面的參數按照map的形式放入
              private Map<String, String> parameters = new HashMap<String, String>();

              
          // 分隔符
              private final static String fileSeparator = System
                  .getProperty(
          "file.separator");

            
          /**
               * 發送帶附件的郵件
               * 
          @param request
               * 
          @param response
               * 
          @throws ServletException
               * 
          @throws IOException
               
          */

              
          public void sendMail(HttpServletRequest request,
                  HttpServletResponse response) 
          throws ServletException, IOException {
              
              
          //因為直接是在容器中.故使用BeanManager將相應的bean獲取,再造型成JavaMailSender
              JavaMailSender sender = (JavaMailSender) BeanManager
                  .getBean(
          "mailSender");

              request.setCharacterEncoding(
          "UTF-8");
              
              
          //添加附件到服務器
              File file = this.doAttachment(request);

              MimeMessage msg 
          = sender.createMimeMessage();
              
          try {
                  MimeMessageHelper helper 
          = new MimeMessageHelper(msg, true,
                      
          "GB2312");
                  
          //發送到哪兒
                  helper.setTo(parameters.get("to"));
                  
          //誰發送的
                  helper.setFrom(parameters.get("from"));
                  
          //發送的主題
                  helper.setSubject(parameters.get("subject"));
                  
          //發送的內容
                  helper.setText(parameters.get("content"),true);
                  
          if (file != null{
                  FileSystemResource fileSource 
          = new FileSystemResource(file
                      .getPath());
                  helper.addAttachment(file.getName(), fileSource);
                  }


                  sender.send(msg);
              }
           catch (Exception e) {
                  e.printStackTrace();
              }


              }


            
          /**
               * 發送簡單郵件
               * 
          @param request
               * 
          @param response
               * 
          @throws ServletException
               * 
          @throws IOException
               
          */

              
          public void sendMail1(HttpServletRequest request,
                  HttpServletResponse response) 
          throws ServletException, IOException {

              JavaMailSender sender 
          = (JavaMailSender) BeanManager
                  .getBean(
          "mailSender");

              SimpleMailMessage mail 
          = new SimpleMailMessage();
              
          try {
                  mail.setTo(
          "xxxx@qq.com");
                  mail.setFrom(
          "xxxx@163.com");
                  mail.setSubject(
          "dosth by xxx");
                  mail.setText(
          "springMail的簡單發送測試");
                  sender.send(mail);
              }
           catch (Exception e) {
                  e.printStackTrace();
              }

              }


            
          /**
               * 添加附件
               * 在添加附件的時候,可以將表格想對應的參數放到一個map中去
               * 在此使用了Jakarta commons的fileupload組件
               * 
          @param request
               * 
          @return
               * 
          @throws ServletException
               * 
          @throws IOException
               
          */

              @SuppressWarnings(
          "unchecked""deprecation" })
              
          public File doAttachment(HttpServletRequest request)
                  
          throws ServletException, IOException {
              File file 
          = null;
              DiskFileItemFactory factory 
          = new DiskFileItemFactory();
              ServletFileUpload upload 
          = new ServletFileUpload(factory);

              
          try {
                  List items 
          = upload.parseRequest(request);
                  Iterator it 
          = items.iterator();
                  
          while (it.hasNext()) {
                  FileItem item 
          = (FileItem) it.next();
                  
          if (item.isFormField()) {
                      parameters.put(item.getFieldName(), item.getString(
          "UTF-8"));
                  }
           else {
                      
          if (item.getName() != null && !item.getName().equals("")) {
                      File tempFile 
          = new File(item.getName());
                      String path 
          = request.getRealPath(fileSeparator)
                          
          + "uploads" + fileSeparator;
                      file 
          = new File(path);
                      
          //建立個文件夾
                      if(!file.exists()){
                          file.mkdir();                
                      }

                      file 
          = new File(path, tempFile.getName());
                      
          //將附件上傳到服務器
                      item.write(file);
                      }

                  }

                  }

              }
           catch (Exception e) {
                  e.printStackTrace();
              }

              
          return file;
              }

              
          }


          2.BeanManager類

          import org.springframework.context.ApplicationContext;

          /**
           * 
          @author zpruan
           * @mail  <xrzp_dh@yahoo.com.cn>
           
          */

          public class BeanManager {

              
          // 應用上下文環境對象
              private static ApplicationContext ac = null;

             
          /**
               * 利用Spring實現聲明式依賴注入,便于直接獲取bean對象
               
          */

              
          public static ApplicationContext getApplicationContext() {
              
          return ac;
              }


            
          /**
               * 返回Spring的ApplicationContext對象
               * 
               * 
          @return
               
          */

              
          public static void setApplicationContext(ApplicationContext acObj) {
              ac 
          = acObj;
              }


            
          /**
               * 根據指定的bean名字來獲取bean
               * 
               * 
          @param key
               * 
          @return
               
          */

              
          public static Object getBean(String key) {
              
          return ac.getBean(key);
              }


          }


           3.xml配置

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
              xmlns:xsi
          ="http://www.w3.org/2001/XMLSchema-instance"
              xmlns:aop
          ="http://www.springframework.org/schema/aop"
              xmlns:tx
          ="http://www.springframework.org/schema/tx"
              xsi:schemaLocation
          ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
                     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
          >

              
          <bean id="mailSender"
                  class
          ="org.springframework.mail.javamail.JavaMailSenderImpl">
                  
          <property name="host">
                      
          <value>smtp.163.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><!-- 用戶名 --></value>
                  
          </property>
                  
          <property name="password">
                      
          <value><!-- 密碼 --></value>
                  
          </property>
              
          </bean>
          </beans>
          posted on 2008-10-18 16:18 xrzp 閱讀(2727) 評論(4)  編輯  收藏 所屬分類: JAVA

          FeedBack:
          # re: 使用spring發送郵件
          2008-10-19 23:36 | 楊愛友
          用你的辦法我沒有得到ApplicationContext對象,我改用new ClassPathXmlApplicationContext("applicationContext.xml")獲取。  回復  更多評論
            
          # re: 使用spring發送郵件
          2008-10-19 23:58 | 楊愛友
          你xml文件里的用戶名和密碼指的是發送者郵箱,可當一個系統投入使用時,這個發送者肯定是當前用戶,所以我覺得發送者的用戶名和密碼不應該設置在xml文件,應該是從前臺獲取,然后再設置到JavaMailSender 對象。  回復  更多評論
            
          # re: 使用spring發送郵件
          2008-10-20 23:37 | sure_xx
          @楊愛友
          ApplicationContext ctx = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()) 是對容器的上下文環境的獲取.我是重寫了DispatcherServlet類,放到init方法中去獲取,然后再set到beanManager中去的.  回復  更多評論
            
          # re: 使用spring發送郵件
          2008-10-20 23:40 | sure_xx
          @楊愛友
          你說的很對哈.如果是個系統的話,登陸之后就有自己的用戶名和密碼.可以將JavaMailSender sender = (JavaMailSender) BeanManager.getBean("mailSender");改為JavaMailSenderImpl sender = (JavaMailSenderImpl)BeanManager.getBean("mailSender");再通過sender的setUsername和setPassword來將用戶名和密碼搞進去.
            回復  更多評論
            

          <2008年10月>
          2829301234
          567891011
          12131415161718
          19202122232425
          2627282930311
          2345678

          常用鏈接

          留言簿(4)

          隨筆分類

          隨筆檔案

          好友的blog

          搜索

          •  

          積分與排名

          • 積分 - 117858
          • 排名 - 499

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 诸暨市| 宣城市| 顺平县| 呼图壁县| 淮阳县| 隆化县| 深圳市| 田林县| 凯里市| 安乡县| 牡丹江市| 讷河市| 屏东县| 稻城县| 济源市| 四子王旗| 山东省| 柯坪县| 珠海市| 天津市| 仲巴县| 定南县| 黄平县| 喀喇沁旗| 宝兴县| 中超| 二连浩特市| 尚义县| 绥棱县| 宜城市| 大关县| 塔城市| 都安| 荥阳市| 咸宁市| 乐昌市| 临颍县| 雅江县| 开封县| 通化县| 金平|