2017-03-17 76 views
0

以前是使用OpenPop測試電子郵件通知。切換到IMAP,並開始查看MailKit。我目前在從Gmail檢索電子郵件正文的純文本字符串時遇到問題。無法使用TextBody檢索電子郵件正文

我的代碼片段至今:

using (var client = new ImapClient()) 
{ 
    var credentials = new NetworkCredential("username", "password"); 
    var uri = new Uri("imaps://imap.gmail.com"); 

    client.Connect(uri); 
    client.AuthenticationMechanisms.Remove("XOAUTH2"); 
    client.Authenticate(credentials); 
    client.Inbox.Open(FolderAccess.ReadOnly); 

    var inboxMessages = client.Inbox.Fetch(0, -1, MessageSummaryItems.Full).ToList(); 

    foreach (var message in inboxMessages) 
    { 
     var messageBody = message.TextBody.ToString(); 
     ... 
    } 

    ... 
} 

從我瞭解的文件至今能的TextBody檢索該郵件正文以純文本格式,如果它的存在。但是,在Visual Studio中進行調試時,我發現這是TextBody的值。

{( 「TEXT」 「普通紙」( 「CHARSET」 「UTF-8」, 「FORMAT」, 「流動」)NIL NIL 「7BIT」 6363 NIL NIL NIL NIL 119)}

是否有一個步驟我我在某處失蹤?這是否意味着從MailKit的角度缺少身體?我也看到了類似的HtmlBody值。

回答

1

Fetch方法只提取摘要有關郵件的信息(如在郵件客戶端中構建郵件列表所需的信息)。

如果要獲取消息,則需要使用GetMessage方法。

像這樣:

using (var client = new ImapClient()) { 
    client.Connect ("imap.gmail.com", 993, true); 
    client.AuthenticationMechanisms.Remove ("XOAUTH2"); 
    client.Authenticate ("username", "password"); 

    client.Inbox.Open (FolderAccess.ReadOnly); 

    var uids = client.Inbox.Search (SearchQuery.All); 

    foreach (var uid in uids) { 
     var message = client.Inbox.GetMessage (uid); 
     var text = message.TextBody; 

     Console.WriteLine ("This is the text/plain content:"); 
     Console.WriteLine ("{0}", text); 
    } 

    client.Disconnect (true); 
} 

現在,如果你想下載郵件正文,你需要使用摘要信息,你是獲取和傳遞中作爲參數到GetBodyPart方法是這樣的:

using (var client = new ImapClient()) { 
    client.Connect ("imap.gmail.com", 993, true); 
    client.AuthenticationMechanisms.Remove ("XOAUTH2"); 
    client.Authenticate ("username", "password"); 

    client.Inbox.Open (FolderAccess.ReadOnly); 

    // Note: the Full and All enum values don't mean what you think 
    // they mean, they are aliases that match the IMAP aliases. 
    // You should also note that Body and BodyStructure have 
    // subtle differences and that you almost always want 
    // BodyStructure and not Body. 
    var items = client.Inbox.Fetch (0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure); 

    foreach (var item in items) { 
     if (item.TextBody != null) { 
      var mime = (TextPart) client.Inbox.GetBodyPart (item.UniqueId, item.TextBody); 
      var text = mime.Text; 

      Console.WriteLine ("This is the text/plain content:"); 
      Console.WriteLine ("{0}", text); 
     } 
    } 

    client.Disconnect (true); 
} 

你可以認爲Fetch方法爲您的IMAP服務器上做一個SQL查詢的元數據˚F或者您的消息以及枚舉參數作爲位域,其中枚舉值可以按位或一起指定哪個IMessageSummary要由Fetch查詢填充。

在上面的例子中,UniqueIdBody bitflags指定我們要填充IMessageSummary結果UniqueIdBody性能。

如果我們想獲得有關讀取/未讀狀態的信息等 - 我們會將MessageSummaryItems.Flags添加到列表中。

注意:兩個BodyBodyStructure枚舉值填充IMessageSummary.Body屬性,但BodyStructure包括被需要,以確定是否一個身體部位是附件或不詳細信息等

相關問題