Greetings.
I've checked out some other question entries here, such as this one, but do not find the same issue as I'm having. Perhaps a guru here has experienced something similar in the past.
Basically, I'm creating an ASP.NET 2.0 web application, which sometimes needs to send out e-mails (using System.Net.Mail), and I'm encountering weird and inconsistent behaviour.
- For all e-mail messages it sends
out, it uses the same e-mail
address, display name and encoding
(
Encoding.UTF8
) in the "From" header (for which aMailAddress
object is created). The display name is always one word, which contains a non-ASCII character. - Each type of message has its own
method generating
MailAddress
andMailAddressCollection
objects before they call a common method with arguments such as from, to, subject, body (which in turn actually transmits the message using aMailMessage
object and anSmtpClient
object). - Most message types are generated properly, with base64 and utf-8 encoded headers (including "From").
- For one particular type of message, however, all fields except "From" are encoded properly. In these messages, the From field's display name isn't encoded at all, causing the non-ASCII character to be displayed as a weird symbol and mail gateways are nagging about bad encoding.
Here is an example of the From field properly encoded:
From: =?utf-8?B?QnJ1a2Vyc8O4a25hZA==?= <munged@munged.tld>
Here is an example of the From field not encoded at all:
From: "Brukers�knad" <munged@munged.tld>
The non-ASCII character is supposed to be "ø", by the way.
Here's the line of code creating the MailAddress
object for From (for the message type which fails encoding of this field:
mailSender = new MailAddress(Settings.SettingFromDB.Email_SenderAddress,
Settings.SettingFromDB.Email_SenderName, Encoding.UTF8);
Similarly, here's a line of code (for the same type of message) creating the MailAddress
object for To (the only difference being it uses a MailAddressCollection
):
mailTo = new MailAddressCollection();
mailTo.Add(new MailAddress(objSøknad.Creator.Email, objSøknad.Creator.FullName,
Encoding.UTF8));
And last but not least, here is the line creating the MailAddress
object for From for a message type in which all fields are always encoded properly (it is identical to the one above!):
mailSender = new MailAddress(Settings.SettingFromDB.Email_SenderAddress,
Settings.SettingFromDB.Email_SenderName, Encoding.UTF8);
The subject is always encoded the same way (Encoding.UTF8
) and the method generating the MailMessage
object and encoding the body is always the same (common method called for all messages). And, the headers that are encoded properly are always base64 encoded in all messages (not quoted-printable).