首页 > 解决方案 > 使用编码 ISO-8859-1 读取电子邮件正文

问题描述

我正在使用 Mailkit 通过 IMAP 阅读一些电子邮件的正文内容。

其中一些电子邮件带有内容类型text/plain和字符集ISO-8859-1,这导致我的代码替换了一些拉丁字符,并且á é í ó ú显然还替换了奇怪的字符,例如...CRLF=E1 =FA =F3 =

var body = message.BodyParts.OfType<BodyPart>().FirstOrDefault(x => x.ContentType.IsMimeType("text", "plain"));
var bodyText = (TextPart)folder.GetBodyPart(message.UniqueId, body);
var bodyContent = bodyText.Text;

使用 Thunderbird 或 Outlook 等电子邮件客户端打开这些电子邮件时没有问题。他们按原样显示这些字符。我希望能够检索这些拉丁字符。

我尝试了一些编码选项但没有成功。

var bodyContent = bodyText.GetText(System.Text.Encoding.ASCII); 
var bodyContent = bodyText.GetText(System.Text.Encoding.UTF-8);

标签: c#encodingcharacter-encodingmailkit

解决方案


我终于可以使用MimeKit中的QuotedPrintableDecoder让它工作了。

var body = message.BodyParts.OfType<BodyPart>().FirstOrDefault(x => x.ContentType.IsMimeType("text", "plain"));
// If it's encoded using quoted-printable we'll need to decode it first. To do so, we'll need the charset.
var charset = body.ContentType.Charset;
var bodyText = (TextPart)folder.GetBodyPart(message.UniqueId, body);
// Decodes the content by using QuotedPrintableDecoder from MimeKit library.
var bodyContent = DecodeQuotedPrintable(bodyText.Text, charset);


static string DecodeQuotedPrintable (string input, string charset)
{
    var decoder = new QuotedPrintableDecoder ();
    var buffer = Encoding.ASCII.GetBytes (input);
    var output = new byte[decoder.EstimateOutputLength (buffer.Length)];
    int used = decoder.Decode (buffer, 0, buffer.Length, output);
    var encoding = Encoding.GetEncoding (charset);
    return encoding.GetString (output, 0, used);
}

推荐阅读