C# 在电子邮件中编码为 UTF-8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16255487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:33:53  来源:igfitidea点击:

encoding to UTF-8 in email

c#.netemailencodingutf-8

提问by Rob Allen

I have a client that is receiving email incorrectly encoded. I am using the System.Net.Mail class and setting the body encoding to UTF-8. I have done a bit of reading and since I have to set the body of the email as a string encoding the data to a UTF-8 byte array really does nothing for me since I have to convert is back to a string that is UTF-16. Correct?

我有一个客户收到的电子邮件编码不正确。我正在使用 System.Net.Mail 类并将正文编码设置为 UTF-8。我做了一些阅读,因为我必须将电子邮件的正文设置为将数据编码为 UTF-8 字节数组的字符串对我来说真的没有任何作用,因为我必须将其转换回 UTF- 16. 正确的?

when I send:Il s'agit d'un message de test pour déterminer comment le système va gérer les messages envoyés à l'aide des caractères fran?ais. Merci et bonne journée.

当我发送:Il s'agit d'un message de test pour déterminer comment le système va gérer les messages envoyés à l'aide des caractères fran?ais。Merci et bonne journée。

They see:*Il s'agit d'un message de test pour d??terminer comment le syst?¨me va g??rer les messages envoy??s ? l'aide des caract?¨res fran?§ais.

他们看到:*Il s'agit d'un message de test pour d??terminer comment le syst?¨me va g??rer les messages envoy??s ? l'aide des caract?¨res fran?§ais。

Merci et bonne journ??e.*

Merci et bonne journ??e.*

I have tried different encodings on the email, but I am really suspecting that the client is incorrectly decoding the email since my email client displays this correctly. Am I missing something? Is there something else that can be done?

我在电子邮件上尝试了不同的编码,但我真的怀疑客户端错误地解码了电子邮件,因为我的电子邮件客户端正确显示了这一点。我错过了什么吗?还有什么可以做的吗?

code below

下面的代码

SmtpMailService.SendMail(string.Empty, toAddress, "[email protected]", "", subject, sb.ToString(), false);

 public static bool SendMail(string fromAddress, string toAddress, string ccAddress, string bccAddress, string subject, string body, bool isHtmlBody)
    {

        if (String.IsNullOrEmpty(toAddress)) return false;
        var toMailAddress = new MailAddress(toAddress);

        var fromMailAddress = new MailAddress(String.IsNullOrEmpty(fromAddress) ? DefaultFromAddress : fromAddress);

        var mailMessage = new MailMessage(fromMailAddress, toMailAddress);

        if (!String.IsNullOrEmpty(ccAddress))
        {
            mailMessage.CC.Add(new MailAddress(ccAddress));
        }

        if (!String.IsNullOrEmpty(bccAddress))
        {
            mailMessage.Bcc.Add(new MailAddress(bccAddress));
        }

        if (!string.IsNullOrEmpty(fromAddress)) mailMessage.Headers.Add("Reply-To", fromAddress);

        mailMessage.Subject = subject;
        mailMessage.IsBodyHtml = isHtmlBody;
        mailMessage.Body = body;
        mailMessage.BodyEncoding = System.Text.Encoding.UTF8;

        var enableSslCfg = ConfigurationManager.AppSettings["Email.Ssl"];
        var enableSsl = string.IsNullOrEmpty(enableSslCfg) || bool.Parse(enableSslCfg);
        var client = new SmtpClient {EnableSsl = enableSsl};

        client.Send(mailMessage);


        return true;
    }

回答by Sanjay Chaudhary

The only way is to replace the character with suitable character as you are using character map and the html is encoding your code to different garbage character

唯一的方法是用合适的字符替换字符,因为您正在使用字符映射并且 html 将您的代码编码为不同的垃圾字符

you can modify your code like :

您可以修改您的代码,如:

WebClient myClient = new WebClient();

        byte[] requestHTML;
        string currentPageUrl = HttpContext.Current.Request.Url.AbsoluteUri;
        UTF8Encoding utf8 = new UTF8Encoding();
        requestHTML = myClient.DownloadData(currentPageUrl);
        var str = utf8.GetString(requestHTML);"
        str = str.Replace("'", "'");

回答by Gy?rgy K?szeg

Your example clearly shows that the text you send has UTF-8 encoding, which is interpreted as Windows-1252 or ISO-8859-1 encoding (see the results of several encoding errors, especially the last row in the table here).

您的示例清楚地表明您发送的文本具有 UTF-8 编码,该编码被解释为 Windows-1252 或 ISO-8859-1 编码(请参阅几个编码错误的结果,尤其是此处表中的最后一行)。

So your code seems to be alright, the problem might be that client side just ignores the encoding of the mail body (for example because they embed it into an HTML page and the wrapper HTML uses the default ISO-8859-1 encoding).

所以您的代码似乎没问题,问题可能在于客户端只是忽略了邮件正文的编码(例如,因为他们将其嵌入到 HTML 页面中,而包装器 HTML 使用默认的 ISO-8859-1 编码)。

Try to send the mail to another provider (eg. Gmail) and check the results. Well configured providers should handle the body encoding.

尝试将邮件发送到其他提供商(例如 Gmail)并检查结果。配置良好的提供者应该处理正文编码。

Solution 1

解决方案1

If the assumptions above are true the error must be fixed on client side. They should either process the body encoding or if it is always UTF-8, they should simply add the following tag into HTML header:

如果上述假设为真,则必须在客户端修复错误。他们应该处理正文编码,或者如果它总是 UTF-8,他们应该简单地将以下标记添加到 HTML 标头中:

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

Solution 2

解决方案2

If you cannot affect the client side at any cost you might want to try to use another encoding:

如果您不能以任何代价影响客户端,您可能想尝试使用另一种编码:

mailMessage.BodyEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");

Please notethat your French example will be correct this way; however, non-Western European languages will not be displayed correctly.

请注意,您的程序会以这种方式正确;但是,非西欧语言将无法正确显示。

回答by edosoft

What finally solved my problem was setting the contenttype on the alternate view. Just setting the msg.BodyEncoding didn't work in (among others) Outlook although Gmail displayed the email correctly.

最终解决了我的问题的是在备用视图上设置内容类型。尽管 Gmail 正确显示了电子邮件,但仅设置 msg.BodyEncoding 在(除其他外)Outlook 中不起作用。

    var msg = new MailMessage()
    msg.BodyEncoding = Encoding.GetEncoding(1252);
    msg.IsBodyHtml = true;
    //htmlBody is a string containing the entire body text
    var htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, new ContentType("text/html"));
    //This does the trick
    htmlView.ContentType.CharSet = Encoding.UTF8.WebName;
    msg.AlternateViews.Add(htmlView);

回答by ALi77

Try:

尝试:

mailMessage.BodyEncoding = UTF8Encoding.UTF8;

instead of:

代替:

mailMessage.BodyEncoding = System.Text.Encoding.UTF8;

回答by josue molina

I had a similar problem with the accents in a mail. My solution was:

我在邮件中的口音也有类似的问题。我的解决方案是:

mail.BodyEncoding = System.Text.Encoding.UTF8;