无法使用TextBody

时间:2017-03-17 23:12:06

标签: c# imap mailkit

以前使用OpenPop测试电子邮件通知。切换到IMAP并立即开始查看MailKit。我目前在从Gmail检索电子邮件正文的纯字符串文本时遇到问题。

到目前为止我的代码片段:

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"" PLAIN"(" CHARSET"" utf-8""格式"&# 34;流动")NIL NIL" 7BIT" 6363 NIL NIL NIL NIL 119)}

我在某处失踪了吗?这是否意味着从MailKit的角度来看,身体缺失了?我也看到了HtmlBody的相似值。

1 个答案:

答案 0 :(得分: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查询以获取消息的元数据,并将MessageSummaryItems枚举参数视为位域,其中枚举值可以是按位的 - 或者一起指定要IMessageSummary查询填充的Fetch个属性。

在上面的示例中,UniqueIdBody位标志指定我们要填充UniqueId结果的BodyIMessageSummary属性。< / p>

如果我们想获取有关已读/未读状态等的信息,我们会将MessageSummaryItems.Flags添加到列表中。

注意:BodyBodyStructure枚举值都填充了IMessageSummary.Body属性,但BodyStructure包含了确定身体部位是否为依恋与否等等。