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

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.

Upvotes: 10

Views: 8651

Answers (2)

Kaizen Programmer
Kaizen Programmer

Reputation: 3818

Try adding the content type to the Alternative View:

AlternateView htmlView = AlternateView.CreateAlternateViewFromString("ä", new ContentType(MediaTypeNames.Text.Html));
htmlView.ContentType.CharSet = Encoding.UTF8.WebName;

Upvotes: 10

Rick Strahl
Rick Strahl

Reputation: 17671

I don't think the BodyEncoding and SubjectEncoding affects reading of messages in any way - it applies to when you send messages and sets the text encoding for the messages and headers when messages are sent.

SmtpClient will read the content-type and charset encoding from messages sent and decode the content of the message and subject according to the encoding it finds in the headers.

If your message is not getting decoded, it seems that the messages are possibly not encoded correctly (or potentially double encoded UTF-8 encoded string getting encoded again by a message encoder), the request headers on the message don't properly match the actual encoding of the message or a charset format that isn't supported in .NET is used.

The only way to know though is to look at the actual raw request trace of a message that fails to see what's actually getting sent.

You might want to set up System.NET tracing for email messages (see http://codepaste.net/j52ktp) or else monitor the TCP/IP stream with something like Wireshark to see what's actually going over the wire and what the headers are instructing the client to do with the data.

FWIW, there's no reason if a message is properly UTF-8 encoded for SmtpClient to not read these messages correctly.

Upvotes: 1

Related Questions