c# - 使用编码 ISO-8859-1 读取电子邮件正文
问题描述
我正在使用 Mailkit 通过 IMAP 阅读一些电子邮件的正文内容。
其中一些电子邮件带有内容类型text/plain
和字符集ISO-8859-1
,这导致我的代码替换了一些拉丁字符,并且á é í ó ú
显然还替换了奇怪的字符,例如...CR
LF
=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);
解决方案
我终于可以使用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);
}
推荐阅读
- android - 使用 Flutter 的 Wifi 细节
- java - 关于带字符数组的 for 循环的基本问题(Java)
- vue.js - 如何使用 axios.post 发布选择输入选项值?
- c# - ModelBinded IList 项为空 OnPost
- reactjs - 上传到 s3 时反应 CORS 被阻止
- python-3.x - 引发 ValueError 并一步登录
- reactjs - 在状态下编辑数组会添加一个新元素而不是更新现有的(反应 JS)
- google-cloud-firestore - Firestore(Angularfire)“合并”或在另一个文档中引用一个文档
- laravel - 如何在 Laravel 中创建额外的可验证模型
- html - 如何在html5的TextBox中自动在4位数字后插入连字符“-”?