MimeKit附件正文编码问题

时间:2019-03-05 14:23:29

标签: c# encoding mime mimekit

我需要在邮箱中获取所有电子邮件。  而且我需要阅读附件的正文以获取信息。  但是我有编码问题,无法解决这个问题。

  

代码示例:

            using (var client = new ImapClient()) 
            {
                client.ServerCertificateValidationCallback = (s, c, h, b) => true;
                client.Connect("imap.secureserver.net", 143, SecureSocketOptions.Auto); // godaddy
                client.Authenticate("username", "password");


                client.Inbox.Open(FolderAccess.ReadOnly);
                IList<UniqueId> uids = client.Inbox.Search(SearchQuery.All);

                foreach (UniqueId uid in uids)
                {
                    MimeMessage message = client.Inbox.GetMessage(uid);

                    foreach (MimeEntity attachment in message.Attachments)
                    {
                        var fileName = "test" + Tools.GenerateRandomString(5);
                        if ((attachment is MessagePart))
                        {
                            var attachmentBody = ((MessagePart)attachment).Message.ToStringNullSafe();
                        }
                    }
                }
            }

附件标题:

  

Content-Type:文本/纯文本; charset =“ utf-8”

     

Content-Transfer-Encoding:带引号的可打印


附件正文中的编码问题

  

主题:Bili = C5 = 9Fim A. = C5 = 9E。

1 个答案:

答案 0 :(得分:0)

您的foreach循环似乎不完整,因为MessagePart无法表示text/plain;charset="utf-8" MIME部分,因此您的代码和结果不匹配。

也就是说,您看到的是内容已编码。您需要对其进行解码:

if (attachment is MimePart) {
    part = (MimePart) attachment;

    using (var stream = File.Create (fileName))
        part.Content.DecodeTo (stream);
}