Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect encoding in e-mails sent with System.Net.Mail.MailMessage

Tags:

c#

email

asp.net

When receiving e-mails sent with System.Net.Mail.MailMessage some recipients seem to have encoding issues with the e-mail. For example charachter ä is displayed as ä. I have set encoding properties:

System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
...
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.SubjectEncoding = System.Text.Encoding.UTF8;

What else can I do?

Update:

If I use the Body property the e-mail is displayed correctly, but when I use the AlternateViews property the e-mail is displayed incorrectly.

Complete code:

SmtpClient smtpClient = new SmtpClient("some.host.com");
MailMessage msg = new MailMessage();
msg.To.Add("[email protected]");
msg.From = new MailAddress("[email protected]", "Name Name");
msg.Subject = "Test";

//Displays as ä
//msg.Body = "ä";

// Displays as ä
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("ä", new ContentType(MediaTypeNames.Text.Html));
msg.AlternateViews.Add(htmlView);

smtpClient.Send(msg);

When sending to Gmail the e-mail is displayed correctly, but when sending to an Exchange server the e-mail is displayed incorrectly. I have tested in .NET 3.5 and 4.5.

like image 975
Kristoffer Jälén Avatar asked May 04 '15 13:05

Kristoffer Jälén


1 Answers

Try adding the content type to the Alternative View:

AlternateView htmlView = AlternateView.CreateAlternateViewFromString("ä", new ContentType(MediaTypeNames.Text.Html));
htmlView.ContentType.CharSet = Encoding.UTF8.WebName;
like image 56
Kaizen Programmer Avatar answered Nov 07 '22 07:11

Kaizen Programmer