smtp.office365.com 主题编码问题

smtp.office365.com subject encoding issues

我尝试使用我专用的 office365 帐户发送电子邮件,但我的主题编码有问题 - 我所有的特殊字符都被替换为“?”。

我使用的代码非常简单,并且可以在 smtp-mail.outlook.com.

的不同测试帐户上正常工作
using (var mailMsg = new MailMessage(sender, recipient))
{
    mailMsg.IsBodyHtml = true;
    mailMsg.Subject = "Hello world żółćąź";
    mailMsg.Body = body;

    using (var smtpClient = new SmtpClient())
    {
        smtpClient.Credentials = new NetworkCredential("email", "password");
        smtpClient.EnableSsl = true;
        smtpClient.Host = "smtp.office365.com";
        smtpClient.Port = 587;

        await smtpClient.SendMailAsync(mailMsg);
    }
}

我尝试设置所有可能的主题编码,但没有成功。将主题字符串转换为 Base64String 也不起作用。还尝试设置 Content-Type header 字符集...我发现的所有解决方案都没有帮助我。也许这是一些仅与 office365 相关的特定 SmtpClient 问题?

并且设置 body 编码也没有帮助

mailMsg.BodyEncoding = Encoding.UTF8;

设置邮件消息的编码,使其支持您使用的字符,因为默认值为 us-ascii:

mailMsg.BodyEncoding = Encoding.UTF8;

我公司的帐户也有同样的问题。以下是我目前的发现:

它看起来像 the Office365 e-mail servers enabled the SMTPUTF8 extension a few months ago,它将 System.Net.Mail.SmtpClient class 的行为更改为发送不同的 SMTP 命令和不同的数据负载。

在我的例子中,当邮件发送到另一个 Office365 帐户时,邮件总是能正常到达,但对于其他帐户,我们收到了来自远程 SMTP 服务器的 e-mail 退回通知,该服务器接受了来自 Office365 的中继 e-mail 邮件.错误类似于 "Invalid data received, expected 7-bit-safe characters"。因此,我可以想象来自 OP 的远程 SMTP 服务器可能会默默地用问号替换低 7 位范围之外的所有字符。

通过 GMail(也激活了 SMTPUTF8 扩展)发送没有问题。

到目前为止,我还没有调试 SmtpClient 参考源以查看发送到 Office365 服务器的内容。因此,根本原因可能是 SmtpClient 发送了一条好消息,而 Office365 "corrupts" 在转发之前发送了一条好消息,而 GMail 继续发送而没有问题;或 SmtpClient 生成错误消息/SMTP session,Office365 静默接受并转发到远程 SMTP 服务器,但 GMail 在中继前即时接受并修复。

无论哪种方式,我都加入了 MailKit and MimeKit libraries using NuGet and use those instead to send my e-mails. These offer SMTP protocol logging to troubleshoot issues and appear to solve the stated problem by properly sending the SMTPUTF8 and 8BITMIME flags as defined in RFC 6531. It does take extra work to read configuration from the usual Web.config or App.config location 但图书馆完成了这项工作。

如果您想继续使用 SmtpClient,那么您应该联系 Microsoft(这是他们的服务和他们的 .NET 运行时),或者 运行 您自己的私人 SMTP 服务器,但没有 SMTPUTF8 中继到远程服务器的扩展。在后一种情况下,SmtpClient 应正确编码所有 headers 和有效负载(尽管这确实意味着您可能无法将 International 值用于 DeliveryFormat 属性 当您想发送给具有国际化 e-mail 地址的人时)。

我们在使用 vmime 库的 Office365 SMTP 服务器上遇到了同样的问题。我们通过禁用 SMTPUTF8 来解决它,因此总是编码非 ascii 字符。

正如 JBert 上面所述,相同的协议适用于 GMail SMTP 服务器。