2010-05-13 14 views
0

嗨我想寫一個Java程序,我將提供我的電子郵件ID和密碼。並且我想讀取到達該電子郵件ID的所有新未讀消息。我不知道如何爲此編寫程序。如何編寫java程序從任何emailid中讀取新郵件

下面的程序適用於gmail。但它不適用於yahoomail,因爲雅虎pop3沒有配置。我想要一個適用於所有電子郵件ID的通用代碼。

import java.io.*; 
import java.util.*; 
import javax.mail.*; 

public class ReadMail { 

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



//  String host = "pop.gmail.com"; 
//  String user = "xyz"; 
//  String password = "12345"; 

     // Get system properties 
     Properties properties = System.getProperties(); 

     // Get the default Session object. 
     Session session = Session.getDefaultInstance(properties, null); 

     // Get a Store object that implements the specified protocol. 
     Store store = session.getStore("pop3s"); 

     //Connect to the current host using the specified username and password. 
     store.connect(host, user, password); 

     //Create a Folder object corresponding to the given name. 
     Folder folder = store.getFolder("inbox"); 

     // Open the Folder. 
     folder.open(Folder.READ_ONLY); 

     Message[] message = folder.getMessages(); 

     // Display message. 
     for (int i = 0; i < message.length; i++) { 

      System.out.println("------------ Message " + (i + 1) + " ------------"); 

      System.out.println("SentDate : " + message[i].getSentDate()); 
      System.out.println("From : " + message[i].getFrom()[0]); 
      System.out.println("Subject : " + message[i].getSubject()); 
      System.out.print("Message : "); 

      InputStream stream = message[i].getInputStream(); 
      while (stream.available() != 0) { 
       System.out.print((char) stream.read()); 
      } 
      System.out.println(); 
     } 

     folder.close(true); 
     store.close(); 
    } 
} 

回答

1

你需要知道的不僅僅是登錄通行證。比如像郵件服務器地址郵件服務器類型端口,用於連接等 你或許應該看看Java Mail API,或者Commons Email

UPD:

您創建一個Session使用Session.getDefaultInstance()方法(這需要連接Properties對象和身份驗證),使用Session.getStore()方法從此Session一個Store,使用Store.getFolder("FOLDER_NAME")方法,開放獲取從商店FolderFolder,使用Folder.open(Folder.READ)方法,並得到所有的信息,使用類似Message[] messages = inboxFolder.getMessages();

這是你W¯¯找到了嗎?

UPD2:

我們根本沒有辦法寫一個通用的計劃,該計劃將與任何郵件供應商合作,只用服務器的路徑,用戶ID和密碼。因爲不同的郵件服務器配置不同。他們在不同的端口上討論不同的協議(imap/pop3/pop3 ssl)。總有一些人,他已經配置了他的郵件服務器,只通過31337端口上的ssl通過imap進行通話,所有其他端口和協議都被禁止。這個人打破了你的計劃。因此,您必須在您的properties對象中指定所有這些屬性。查看here的屬性,你必須指定。

UPD3:

關於第二個想法,你確實有一個選項。只需嘗試使用不同的協議連接到服務器。如果這沒有幫助,開始迭代通過端口。適合的是你的配置。 如果這真的是你想要的。

0

您需要javax.mail包及其文檔。閱讀文檔。然後你知道。

+0

我看過了,但現在還不清楚 – 2010-05-13 10:13:25

0

有兩種方法可以做到這一點:

1)谷歌提供的API來訪問郵件,你可以使用該庫,它提供了你的郵件更多的控制。見這裏:http://code.google.com/apis/gmail/。以同樣的方式嘗試其他電子郵件提供商。

2)簡單的郵件客戶端(你可以很容易地發現它),但你需要看標題,以確定哪些郵件讀/未讀等。

0

您需要一個註冊表,您可以獲取給定郵件服務的屬性。

例如,而不是指定POP3主機,你可以指定一個屬性文件,將包含主機,端口,協議等的名稱...

如果你的屬性文件中包含該協議,例如mail.store.protocol = pop3,你可以使用session.getStore()(沒有參數),同樣的代碼可以用於pop3,imap,pop3s,imaps。

相關問題