Search code examples
c#smtpsmtpclient

Office365 SMTP server replaces international characters in subject


I'm using an Office365 smtp server to send out mails and it has been working flawlessly for a long time now. However, yesterday a problem occurred in the mails we are sending.

International characters such as æøåöü are being replaced in the subject with something that does not make much sense to me.

æ -> C&

ø -> C8

å -> C%

I've tried changing the Delivery Format from International to SevenBit and that works, which is odd, however that just leaves me with another issue which is that "to" emails cannot contain international characters.

I'm inclined to think that the issue is not in the code itself but the SMTP server instead.

This is a simplified version of my code that I've managed to reproduce the issue with:

        static void Main(string[] args)
        {
            var client = new SmtpClient();
            var mailAddress = new MailAddress("abc@domain.com");

            var msg = new MailMessage
            {
                From = mailAddress,
                To = { "receiving-mail@domain.com" },
                ReplyToList = { new MailAddress("receiving-mail@domain.com", "Testing") },
                Subject = "This is a test with Ææ Øø Åå",
                Body = "Test",
                IsBodyHtml = true,
            };

            client.Send(msg);

            Console.WriteLine("sent");
            Console.ReadKey();
        }

And this is the configuration settings in the Web.Config file

    <mailSettings>
      <smtp deliveryMethod="Network" deliveryFormat="International">
        <network defaultCredentials="false" enableSsl="true" host="smtp.office365.com" port="587" password="censoredforstackoverflow" userName="censoredforstackoverflow" />
      </smtp>
    </mailSettings>

Solution

  • We ended up with a hacky solution that only potentially gives messy subjects to users with addresses that contain international characters. By checking the address for international characters and setting the SmtpDeliveryFormat to International.

    smtpClient.DeliveryFormat = SmtpDeliveryFormat.International;
    

    The regex:

    var emailWithoutInternationalCharsRegex = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]+.$";
    

    It works well enough for us as only 1/1000 of our users have international characters in their address and it is only the subject of the e-mail that has the problem.