2017-05-01 40 views
-2

我試圖將收件箱中的電子郵件複製到文本文件中,然後在此文本文件中搜索。如果這個詞存在,我將使用這個詞來查詢電子郵件ID從數據庫最終轉發這封郵件到這個電子郵件ID。 我的問題是我不能將電子郵件複製到文本文件。味精變量總是空 這是我的代碼:如何將電子郵件正文保存到C#文本文件中

using (Pop3Client client = new Pop3Client()) 
{ 
    client.Connect("pop.gmail.com", 995, true); 
    client.Authenticate("[email protected]", "pasword", AuthenticationMethod.UsernameAndPassword); 

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

    for (int i = messageCount; i > 0; i--) 
    { 
     string msg = client.GetMessage(i).MessagePart.GetBodyAsText().ToString(); 

     System.IO.File.WriteAllText(@"d:\\My File2.log", msg.ToString()); 
     var body = System.IO.File.ReadLines(@"d:\\My File2.log"); 
     if (body.Contains("cusotmer ID: X")) 
     { 
      getemailadress(); 
      sendemail(); 
     } 
    } 
} 
+3

你忘了問一個問題嗎? – Steve

+0

你的代碼不工作的方式是什麼?描述問題。 – David

+2

爲什麼要將郵件正文寫入文件,然後再次閱讀以搜索文本。只需從msg變量中讀取它,然後將其保存爲成功或失敗。 – athar13

回答

0

,你可以使用此代碼: VAR mailbody = ASCIIEncoding.ASCII.GetString(message.RawMessage); 這樣的:

using (Pop3Client client = new Pop3Client()) 
{ 
    client.Connect("pop.gmail.com", 995, true); 
    client.Authenticate("[email protected]", "pasword", AuthenticationMethod.UsernameAndPassword); 

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

    for (int i = messageCount; i > 0; i--) 
    { 

string msg = ASCIIEncoding.ASCII.GetString(client.GetMessage(i).RawMessage); 


     System.IO.File.WriteAllText(@"d:\\My File2.log", msg); 
     var body = System.IO.File.ReadLines(@"d:\\My File2.log"); 
     if (body.Contains("cusotmer ID: X")) 
     { 
      getemailadress(); 
      sendemail(); 
     } 
    } 
} 

而且,建議:停止調用的ToString()對已經字符串對象。

我不明白你爲什麼要將messageBody保存到TextFile。因爲WriteAllText函數將在每個循環上覆蓋此文件。 所以你不會找到你的所有消息這個方法的結束。您只能在文本文件中找到最後一個消息正文。你注意到了嗎?

+0

即時嘗試將messageBody保存到TextFile,因爲我需要從此messageBody中選擇特定的單詞。 – marwen1

+0

仍然我認爲你不需要保存messageBody到任何文件。你可以在內存中找到,選擇或操縱你的messageBody。 – wikiCan

相關問題