【问题标题】:Incorrect encoding in e-mails sent with System.Net.Mail.MailMessage使用 System.Net.Mail.MailMessage 发送的电子邮件中的编码不正确
【发布时间】:2015-07-13 22:17:23
【问题描述】:

在接收使用System.Net.Mail.MailMessage 发送的电子邮件时,某些收件人似乎对电子邮件有编码问题。例如字符 ä 显示为 ä。我已经设置了编码属性:

System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
...
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.SubjectEncoding = System.Text.Encoding.UTF8;

我还能做什么?

更新:

如果我使用Body 属性,则电子邮件显示正确,但当我使用AlternateViews 属性时,电子邮件显示不正确。

完整代码:

SmtpClient smtpClient = new SmtpClient("some.host.com");
MailMessage msg = new MailMessage();
msg.To.Add("someone@host.com");
msg.From = new MailAddress("name@host.com", "Name Name");
msg.Subject = "Test";

//Displays as ä
//msg.Body = "ä";

// Displays as ä
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("ä", new ContentType(MediaTypeNames.Text.Html));
msg.AlternateViews.Add(htmlView);

smtpClient.Send(msg);

发送到 Gmail 时,电子邮件显示正确,但发送到 Exchange 服务器时,电子邮件显示不正确。我已经在 .NET 3.5 和 4.5 中进行了测试。

【问题讨论】:

标签: c# asp.net email


【解决方案1】:

尝试将内容类型添加到备用视图:

AlternateView htmlView = AlternateView.CreateAlternateViewFromString("ä", new ContentType(MediaTypeNames.Text.Html));
htmlView.ContentType.CharSet = Encoding.UTF8.WebName;

【讨论】:

  • 不知道这是否与 OP 有关,但仔细查看原始消息内容足以让我理解为什么这个答案是有意义的。毕竟,我的消息正文被编码为 AlternateView,因此设置 BodyEncoding 可以完成工作,但它是无文本正文:正文中没有文本,但在 AlternateView 中。
  • mail.Headers.Add("Content-Type", "content=text/html; charset=\"UTF-8\"");这应该在没有备用视图的情况下也可以工作(在 html 的正文标头中使用元标记设置编码不起作用,因为 MailMessage 类从正文中删除了元标记)。
【解决方案2】:

我认为 BodyEncoding 和 SubjectEncoding 不会以任何方式影响消息的阅读 - 它适用于您发送消息并在发送消息时设置消息和标题的文本编码。

SmtpClient 将从发送的消息中读取内容类型和字符集编码,并根据在标头中找到的编码解码消息的内容和主题。

如果您的消息没有被解码,似乎消息可能没有正确编码(或者可能双重编码的 UTF-8 编码字符串被消息编码器再次编码),消息上的请求标头不正确匹配消息的实际编码或使用 .NET 不支持的字符集格式。

但是,唯一知道的方法是查看无法查看实际发送的消息的实际原始请求跟踪。

您可能希望为电子邮件消息设置 System.NET 跟踪(请参阅http://codepaste.net/j52ktp),或者使用 Wireshark 之类的东西监视 TCP/IP 流,以查看实际通过网络传输的内容以及标头指示客户端的内容与数据有关。

FWIW,如果消息被正确地 UTF-8 编码,SmtpClient 没有理由无法正确读取这些消息。

【讨论】:

    猜你喜欢
    • 2015-02-17
    • 2012-08-09
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 2011-08-21
    • 1970-01-01
    • 2013-06-01
    相关资源
    最近更新 更多