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?
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.
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.
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;
}
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With