我有一个客户正在接收错误编码的电子邮件。我正在使用 System.Net.Mail 类并将正文编码设置为 UTF-8。我已经阅读了一些内容,因为我必须将电子邮件的正文设置为将数据编码为 UTF-8 字节数组的字符串,这对我没有任何帮助,因为我必须将其转换回 UTF- 字符串16.正确吗?
当我发送时: Il s'agit d'un message de test pour determiner comment le system 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.*
我在电子邮件上尝试了不同的编码,但我真的怀疑客户端错误地解码了电子邮件,因为我的电子邮件客户端正确显示了这一点。我错过了什么吗?还有什么可以做的吗?
下面的代码
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;
}
最佳答案
最终解决我的问题的是在备用 View 上设置内容类型。尽管 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);
关于c# - 在电子邮件中编码为 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16255487/