Java Mail(三):Session、Message詳解


http://blog.csdn.net/ghsau/article/details/17909093

*************************************

 

       本文來自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/17909093,轉載請注明。
       上篇文章介紹了JavaMail並實現了一個發送郵件的簡單示例,JavaMail API使用上非常靈活,比如,服務器信息可以設置到Session中,也可以設置到Transport中,收件人可以設置到Message中,也可以設置到Transport中,如何使用,取決於我們應用程序中的實際情況。本文詳細的介紹一下這三個類的主要方法。

Session

 
       Session用於收集JavaMail運行過程中的環境信息,它可以創建一個單例的對象,也可以每次創建新的對象,Session沒有構造器,只能通過如下方法創造實例:
static Session getDefaultInstance(Properties props)
          Get the default Session object.
static Session getDefaultInstance(Properties props,Authenticator authenticator)
          Get the default Session object.
static Session getInstance(Properties props)
          Get a new Session object.
static Session getInstance(Properties props,Authenticator authenticator)
          Get a new Session object.

       getDefaultInstance得到的始終是該方法初次創建的缺省的對象,而getInstance得到的始終是新的對象,Authenticator的使用后面會說到。通過Session可以創建Transport(用於發送郵件)和Store(用於接收郵件),Transport和Store是JavaMail API中定義好的接口,通過上文我們知道JavaMail分為API和service provider兩部分,API定義了相關接口(eg.:Transport and Store),service provider中實現了這些接口,這些實現類配置在名為javamail.providersjavamail.default.providers的文件中,該文件放在mail.jar/smtp.jar/pop3.jar/imap.jar中的META-INF下,文件內容格式如:

    # JavaMail IMAP provider Sun Microsystems, Inc  
    protocol=imap; type=store; class=com.sun.mail.imap.IMAPStore; vendor=Sun Microsystems, Inc;  
    protocol=imaps; type=store; class=com.sun.mail.imap.IMAPSSLStore; vendor=Sun Microsystems, Inc;  
    # JavaMail SMTP provider Sun Microsystems, Inc  
    protocol=smtp; type=transport; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc;  
    protocol=smtps; type=transport; class=com.sun.mail.smtp.SMTPSSLTransport; vendor=Sun Microsystems, Inc;  
    # JavaMail POP3 provider Sun Microsystems, Inc  
    protocol=pop3; type=store; class=com.sun.mail.pop3.POP3Store; vendor=Sun Microsystems, Inc;  
    protocol=pop3s; type=store; class=com.sun.mail.pop3.POP3SSLStore; vendor=Sun Microsystems, Inc;  

     每一行聲明了協議名稱、類型、實現類、供應商、版本等信息,如果需要自己實現相應的協議,必須按照該格式配置好,Java Mail API中才能正確的調用到。Session中提供的創建Trasnsport和Store的方法如下:

 Store getStore()
          Get a Store object that implements this user's desired Store protocol.
 Store getStore(Provider provider)
          Get an instance of the store specified by Provider.
 Store getStore(String protocol)
          Get a Store object that implements the specified protocol.
 Store getStore(URLName url)
          Get a Store object for the given URLName.
 Transport getTransport()
          Get a Transport object that implements this user's desired Transport protcol.
 Transport getTransport(Address address)
          Get a Transport object that can transport a Message of the specified address type.
 Transport getTransport(Provider provider)
          Get an instance of the transport specified in the Provider.
 Transport getTransport(String protocol)
          Get a Transport object that implements the specified protocol.
 Transport getTransport(URLName url)
          Get a Transport object for the given URLName.

       可以看到,重載了很多,這些方法最終都會去解析上文提到的配置文件,找到對應配置信息。

 

Message


       Message是郵件的載體,用於封裝郵件的所有信息,Message是一個抽象類,已知的實現類有MimeMessage。一封完整的郵件都有哪些信息呢?我們打開一個郵件客戶端,我用的是FoxMail,新建一封郵件,如下圖所示:

       這就是一封完整的郵件包含的所有信息,默認情況下是沒有暗送和回復設置的,可以通過菜單欄-->查看-->暗送地址/回復地址來顯示出來,回復地址默認情況下為發件人,暗送是比較猥瑣的發郵件方式,暗送郵件除了被暗送者,沒有人能知道暗送給誰了,郵件頭信息中也不會記錄。下面來看下Message中設置郵件信息的一些方法。

發件人

abstract  void setFrom()
          Set the "From" attribute in this Message.
abstract  void setFrom(Address address)
          Set the "From" attribute in this Message.
       現在大多數SMTP服務器要求發件人與連接賬戶必須一致,否則會拋出驗證失敗的異常,這樣是防止用戶偽裝成其它人的賬戶惡意發送郵件。

收件人/抄送人/暗送人

void setRecipient(Message.RecipientType type,Address address)
          Set the recipient address.
abstract  void setRecipients(Message.RecipientType type,Address[] addresses)
          Set the recipient addresses.
       第一個方法設置單個人,第二個方法設置多個人。方法中第一個參數涉及到另一個類RecipientType,該類是Message的靜態內部類,期內有三個常量值:
static Message.RecipientType BCC
          The "Bcc" (blind carbon copy) recipients.
static Message.RecipientType CC
          The "Cc" (carbon copy) recipients.
static Message.RecipientType TO
          The "To" (primary) recipients.
       TO - 收件人;CC - 抄送人;BCC - 暗送人。

回復人

 void setReplyTo(Address[] addresses)
          Set the addresses to which replies should be directed.
       設置收件人收到郵件后的回復地址。

標題

abstract  void setSubject(String subject)
          Set the subject of this message.
       設置郵件標題/主題。

內容

 void setContent(Multipart mp)
          This method sets the given Multipart object as this message's content.
 void setContent(Object obj,String type)
          A convenience method for setting this part's content.
 void setText(String text)
          A convenience method that sets the given String as this part's content with a MIME type of "text/plain".
       設置郵件文本內容、HTML內容、附件內容。
 

示例

 

       下面來看一個稍復雜點的示例:

    public class JavaMailTest2 {  
      
        public static void main(String[] args) throws MessagingException {  
            Properties props = new Properties();  
            // 開啟debug調試  
            props.setProperty("mail.debug", "true");  
            // 發送服務器需要身份驗證  
            props.setProperty("mail.smtp.auth", "true");  
            // 設置郵件服務器主機名  
            props.setProperty("mail.host", "smtp.163.com");  
            // 發送郵件協議名稱  
            props.setProperty("mail.transport.protocol", "smtp");  
              
            // 設置環境信息  
            Session session = Session.getInstance(props, new Authenticator() {  
                // 在session中設置賬戶信息,Transport發送郵件時會使用  
                protected PasswordAuthentication getPasswordAuthentication() {  
                    return new PasswordAuthentication("java_mail_001", "javamail");  
                }  
            });  
              
            // 創建郵件對象  
            Message msg = new MimeMessage(session);  
            // 發件人  
            msg.setFrom(new InternetAddress("java_mail_001@163.com"));  
            // 多個收件人  
            msg.setRecipients(RecipientType.TO, InternetAddress.parse("java_mail_002@163.com,java_mail_003@163.com"));  
            // 抄送人  
            msg.setRecipient(RecipientType.CC, new InternetAddress("java_mail_001@163.com"));  
            // 暗送人  
            msg.setRecipient(RecipientType.BCC, new InternetAddress("java_mail_004@163.com"));  
              
            // 主題  
            msg.setSubject("中文主題");  
            // HTML內容  
            msg.setContent("<div align=\"center\">你好啊</div>", "text/html;charset=utf-8");  
              
            // 連接郵件服務器、發送郵件、關閉連接,全干了  
            Transport.send(msg);  
        }  
      
    }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM