JAVA+TOMCAT網站部署第三天——郵件發送

1.需要mail.jar和activation.jar可在j2ee的lib裏面找到

C:/Sun/AppServer/lib

2.要在tomcat中使用,需要將這兩個jar放到tomcat/common/lib裏面,並添加到classpath中

import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;

   /*--  設置屬性  --*/
   properties = System.getProperties();
   properties.put("mail.smtp.auth", strAuthen);
   properties.put("mail.smtp.host", strHost);

   /*--  密碼驗證  --*/
   SmtpAuthenticator sa = new SmtpAuthenticator(strUsr, strPwd);
   Session session = Session.getInstance(properties,sa);
   session.setDebug(false);

   /*-- 構造郵件  --*/
   Message msg = new MimeMessage(session);
   msg.setSentDate(new Date());
   msg.setFrom(new InternetAddress(strFrom));
   msg.setRecipient(Message.RecipientType.TO,new  InternetAddress(strTo));
   msg.setSubject(strSubject);
   msg.setContent(strBody,"text/plain;charset=Gb2312");

   /*--  傳送郵件 --*/
   transport = session.getTransport("smtp");
   if(strAuthen.equals("true"))//是否需要驗證
   {
    transport.connect(strHost, strUsr, strPwd);
    transport.sendMessage(msg, msg.getAllRecipients());
   }
   else
   {
    transport.send(msg);
   }
   transport.close();
3.JSP中使用

  SendMail sender = new SendMail("[email protected]",  //--發信人
          "[email protected]",  //--收信人
          "this 劉國強 Title",  //--標題
          "this 劉國強 body",   //--內容
          null);     //--附件
  sender.putAuthentication("smtp.sohu.com",    //--smtp服務器
        "ohahu",      //--用戶名
        "",      //--密碼不要忘記輸了
        "true");      //是否需要驗證
   sender.startSend();   
4.需要改進的地方,沒有加入附件的代碼,可以參考

http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=12942

其中的strAttach應該是附件的路徑信息。

接下來的任務:

1.完善附件添加部分內容

2.通過郵件驗證用戶註冊申請及密碼修改功能

2.文件上傳代碼

3.數據庫記錄按照XML文件顯示,及數據庫生成目錄樹

7月25日添:郵件附件的添加

爲了一個附件的內容加一個第四天實在不值得,主要代碼如下:

    /*--  添加附件  --*/
    Multipart multiPart  = new MimeMultipart();
    //信件內容
    MimeBodyPart textBody = new MimeBodyPart();
    textBody.setText(strBody);
    multiPart.addBodyPart(textBody);
    //信件附件
    Enumeration elemFile = vFile.elements();//Vector vFile;用vFile.addElement(String newFile);添加附件
    iAttachCount   = 0;
    while(elemFile.hasMoreElements())
    {
     String strFileName = elemFile.nextElement().toString();//附件的路徑
     File file   = new File(strFileName);
     if(!file.exists())//判斷文件是否存在
      continue;
     iAttachCount++;
     MimeBodyPart fileBody = new MimeBodyPart();
     FileDataSource fileData = new FileDataSource(strFileName);
     fileBody.setDataHandler(new DataHandler(fileData));
     fileBody.setFileName(fileData.getName());
     multiPart.addBodyPart(fileBody);
    }
    vFile.removeAllElements();

    msg.setContent(multiPart);
   }

有了這部分內容,就不用再用上面msg.setContent(strBody,"text/plain;charset=Gb2312");部分了,不過如果沒有附件也用MimeBodyPart,在接收郵件的時候同樣會顯示出有附件,因此,沒有附件最好用setContent函數構造郵件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章