在电子邮件中编码到UTF-8

时间:2022-06-24 22:18:45

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。邮件类,并将主体编码设置为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.

当我发送:它有一个测试信息,为系统做评论,我们会将消息发送给一个法国特性的助手。谢谢祝你journee。

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.

他们看到:*需要s d一个消息de测试倒dA©判决发表评论勒systA¨我va gA©r les消息envoyA©年代l 'aide des caractA¨res franA§ais。

Merci et bonne journée.*

谢谢et女佣journA©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, "emailaddress@emai.com", "", 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;
    }

3 个解决方案

#1


2  

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.

尝试将邮件发送到另一个提供者(如。并检查结果。配置良好的提供者应该处理主体编码。

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 note that your French example will be correct this way; however, non-Western European languages will not be displayed correctly.

请注意,您的法语示例将以这种方式正确;然而,非西方欧洲语言将不会被正确显示。

#2


1  

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("’", "'");

#3


1  

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.

最后解决我的问题的是在另一个视图上设置contenttype。只是设置味精。虽然Gmail正确地显示了电子邮件,但是bodycoding在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);

#1


2  

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.

尝试将邮件发送到另一个提供者(如。并检查结果。配置良好的提供者应该处理主体编码。

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 note that your French example will be correct this way; however, non-Western European languages will not be displayed correctly.

请注意,您的法语示例将以这种方式正确;然而,非西方欧洲语言将不会被正确显示。

#2


1  

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("’", "'");

#3


1  

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.

最后解决我的问题的是在另一个视图上设置contenttype。只是设置味精。虽然Gmail正确地显示了电子邮件,但是bodycoding在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);