2012-05-15 77 views
8

我正在使用OpenPop.net嘗試解析我們從給定收件箱中的所有電子郵件中的鏈接。我發現這個方法來獲取所有的消息:OpenPop.net獲取實際消息文本

public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password) 
    { 
     // The client disconnects from the server when being disposed 
     using (Pop3Client client = new Pop3Client()) 
     { 
      // Connect to the server 
      client.Connect(hostname, port, useSsl); 

      // Authenticate ourselves towards the server 
      client.Authenticate(username, password); 

      // Get the number of messages in the inbox 
      int messageCount = client.GetMessageCount(); 

      // We want to download all messages 
      List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount); 

      // Messages are numbered in the interval: [1, messageCount] 
      // Ergo: message numbers are 1-based. 
      // Most servers give the latest message the highest number 
      for (int i = messageCount; i > 0; i--) 
      { 
       allMessages.Add(client.GetMessage(i));      
      } 

      client.Disconnect(); 

      // Now return the fetched messages 
      return allMessages; 
     } 
    } 

現在我通過每封郵件試圖循環,但我似乎無法弄清楚如何做到這一點,我有這個迄今爲止對我的按鈕:

private void button7_Click(object sender, EventArgs e) 
    { 

     List<OpenPop.Mime.Message> allaEmail = FetchAllMessages("pop3.live.com", 995, true, "[email protected]", "xxxxx"); 

     var message = string.Join(",", allaEmail); 
     MessageBox.Show(message); 
    } 

我將如何循環通過allaEmail中的每個條目,以便我可以將其顯示在MessageBox中?

回答

25

我可以看到您使用OpenPop主頁中的fetchAllEmail example。主頁上也有一個類似的例子showing how to get body text

您可能還想看看電子郵件的實際結構。 A email introduction就是爲了這個目的而存在的。

說了這些,我會做類似於下面的代碼。

private void button7_Click(object sender, EventArgs e) 
{ 
    List<OpenPop.Mime.Message> allaEmail = FetchAllMessages(...); 

    StringBuilder builder = new StringBuilder(); 
    foreach(OpenPop.Mime.Message message in allaEmail) 
    { 
     OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion(); 
     if(plainText != null) 
     { 
      // We found some plaintext! 
      builder.Append(plainText.GetBodyAsText()); 
     } else 
     { 
      // Might include a part holding html instead 
      OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion(); 
      if(html != null) 
      { 
       // We found some html! 
       builder.Append(html.GetBodyAsText()); 
      } 
     } 
    } 
    MessageBox.Show(builder.ToString()); 
} 

我希望這可以幫助你在路上。請注意,OpenPop也有online documentation

+1

哇謝謝你foens!那正是我所追求的! :)複選框提交 – user1213488

+0

html.GetBodyAsText()提供了一個異常,表示objectreference未設置爲實例。但我使用FindFirstPlainTextVersion()獲取值,然後使用plainText.GetBodyAsText()知道爲什麼? – Antony

0

這是我做的:

string Body = msgList[0].MessagePart.MessageParts[0].GetBodyAsText(); 
      foreach(string d in Body.Split('\n')){ 
       Console.WriteLine(d);      
      } 

希望它能幫助。