2017-03-17 83 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包括被需要,以确定是否一个身体部位是附件或不详细信息等

相关问题