圖3 mail.Part接口的UML圖 圖3表示在前面例子中建立的一個Message,它既可以是一個消息,也可以是一個消息部分,因為它實現了Part接口。對于任何部分,你都能得到它的內容(任何Java對象),并且在發送的是一個簡單文本消息的情況下,內容對象可能是一個String。對于多部分消息,內容可能是類型Multipart,由此我們可以得到單獨的正文部分,它本身就實現了Part接口 實際上,當你看過SimpleReceiver類的代碼之后,你會發現一切都變得很明朗。我們用三部分內容來介紹SimpleReceiver類:第一部分,類的定義以及從命令行獲取連接細節信息的main()方法;第二部分,捕捉和查看進來消息的receive()方法;第三部分,打印頭信息和每個消息內容的PRintMessage()方法。 下面是第一部分: package com.lotontech.mail; import javax.mail.*; import javax.mail.internet.*; import java.util.*; import java.io.*; /** * A simple email receiver class. */ public class SimpleReceiver /** * Main method to receive messages from the mail server specified * as command line arguments. */ public static void main(String args[]) { try { String popServer=args[0]; String popUser=args[1]; String popPassWord=args[2]; receive(popServer, popUser, popPassword); } catch (Exception ex) { System.out.println("Usage: java com.lotontech.mail.SimpleReceiver"+" popServer popUser popPassword"); } System.exit(0); } 現在我們使用命令行來運行它(記住用你的email設置替換命令行參數): java com.lotontech.mail.SimpleReceiver pop.myIsp.net myUserName myPassword receive()方法從main()方法中調用,它依次打開你的POP3信箱檢查消息,每次都調用printMessage()。代碼如下: /** * "receive" method to fetch messages and process them. */ public static void receive(String popServer, String popUser , String popPassword) { Store store=null; Folder folder=null; try { // -- Get hold of the default session -- Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); // -- Get hold of a POP3 message store, and connect to it -- store = session.getStore("pop3"); store.connect(popServer, popUser, popPassword); // -- Try to get hold of the default folder -- folder = store.getDefaultFolder(); if (folder == null) throw new Exception("No default folder"); // -- ...and its INBOX -- folder = folder.getFolder("INBOX"); if (folder == null) throw new Exception("No POP3 INBOX"); // -- Open the folder for read only -- folder.open(Folder.READ_ONLY); // -- Get the message wrappers and process them -- Message[] msgs = folder.getMessages(); for (int msgNum = 0; msgNum < msgs.length; msgNum++) { printMessage(msgs[msgNum]); } } catch (Exception ex) { ex.printStackTrace(); } finally { // -- Close down nicely -- try { if (folder!=null) folder.close(false); if (store!=null) store.close(); } catch (Exception ex2) {ex2.printStackTrace();} } } 請注重:你從session中得到一個POP3消息存儲封裝器,然后使用最初在命令行上鍵入的mail設置跟它連接。 一旦連接成功,你就得到了一個默認文件夾的句柄,在這里使用的是INBOX文件夾,它保存了進來的消息。你可以打開這個只讀的INBOX信箱,然后一個一個的讀取消息。 另外,你可能想知道是否你能夠以寫的方式打開這個INBOX信箱。假如你想為這些消息做標記或者從服務器上刪除,你可以做得到。不過在我們的這個例子中,你只能查看消息。 最后,在上面的代碼中,你做到了當查看完畢后關閉文件夾以及消息存儲,然后留下printMessage()方法來完成這個類的剩余部分。 打印消息 在這一部分,很有必要討論前面提到的javax.mail.Part接口。 下面的代碼讓你明白怎樣隱含地把消息轉換為它的Part接口并且把它賦給messagePart變量。對于只有一部分的消息,你現在需要打印一些信息。 假如調用messagePart.getContent()來生成一個Multipart實例,你知道你正在處理一個多部分消息;在這種情況下,你正在通過getBodyPart(0)來得到第一個多部分消息并且打印它。 當然你還要知道是否你已經得到了這個消息本身,還是僅僅是消息正文的第一部份。只有當內容是普通文本或者Html時,你才可以打印該消息,這是通過一個InputStream來完成的。 /** * "printMessage()" method to print a message. */ public static void printMessage(Message message) { try { // Get the header information String from=((InternetAddress)message.getFrom()[0]).getPersonal(); if (from==null) from=((InternetAddress)message.getFrom()[0]) .getAddress(); System.out.println("FROM: "+from); String subject=message.getSubject(); System.out.println("SUBJECT: "+subject); // -- Get the message part (i.e. the message itself) -- Part messagePart=message; Object content=messagePart.getContent(); // -- or its first body part if it is a multipart message -- if (content instanceof Multipart) { messagePart=((Multipart)content).getBodyPart(0); System.out.println("[ Multipart Message ]"); } // -- Get the content type -- String contentType=messagePart.getContentType(); // -- If the content is plain text, we can print it -- System.out.println("CONTENT:"+contentType); if (contentType.startsWith("text/plain") contentType.startsWith("text/html")) InputStream is = messagePart.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(is)); String thisLine=reader.readLine(); while (thisLine!=null) { System.out.println(thisLine); thisLine=reader.readLine(); } } System.out.println("-----------------------------"); } catch (Exception ex) { ex.printStackTrace(); } } } 為了簡單起見,我假設消息本身或者消息正文的第一部份是可以打印的。對于真正的應用軟件,可能你想要依次檢查消息正文的每一部分,并且對每一部分采取相應的行動-打印或者是保存到磁盤,這取決于內容的類型。 當你從消息存儲中得到每個消息時,你實際上已經得到了一個輕量級的封裝器。數據內容的獲取是每申請一次就讀取一次-這對于你只想下載消息頭時很有用。 SimpleReceiver測試 讓我們對SimpleReceiver做一次測試。為了讓它有東西可以接收,我發送圖4所示的消息(注重:消息由文本和一個附件組成) 圖4 用于SimpleReceiver的測試消息 一旦接收到消息,就把該消息認為是一個多部分消息。打印的文本如下: FROM: Tony Loton SUBJECT: Number 1 [ Multipart Message ] CONTENT:text/plain; charset="iso-8859-1" Attachment 1 from Tony Loton. ----------------------------- 把你的消息送出去 為了有趣一點,并且說明JavaMail APIs的一個新奇的用法,我現在簡要介紹一下我的談話email項目。在做這個試驗之前你需要得到lotontalk.jar文件,并把它加到你的classpath中去,添加方法如下: set CLASSPATH=%CLASSPATH%;lotontalk.jar 你也需要在SimpleReceiver類中兩個地方做代碼修改。首先在receive()方法里面,把以下代碼: // -- Get the message wrappers and process them -- Message[] msgs = folder.getMessages(); for (int msgNum = 0; msgNum < msgs.length; msgNum++) { printMessage(msgs[msgNum]); } 替換為: // -- Get the message wrappers and process them -- Message[] msgs = folder.getMessages(); for (int msgNum = 0; msgNum < msgs.length; msgNum++) { printMessage(msgs[msgNum]); speakMe