1st May, 2011

Sending Unicode based HTML emails.

Email is a tricky subject. Even if your server and client supports Unicode, you can't guarantee every server between them does. All it needs is to hop through one 7bit server and your beautiful HTML email is mangled.

I use the following bit of C# code to convert any non 7 bit ASCII character to the HTML character entity which converts into the special characters when the client views it. Brilliant.

private string EncodeExtendedCharacters(string input)
{
    StringBuilder result = new StringBuilder();

    foreach(char loopChar in input)
    {
        int characterIndex = Convert.ToInt32(loopChar);
        if(characterIndex > 127)
            result.Append(String.Concat("&", _htmlCharacters[characterIndex], ";"));
        else
        result.Append(loopChar);
    }

    return result.ToString();
}

 

The opinions expressed here are my own and not those of my employer.