How to properly add CSS to MailMessage

I am writing HTML code in MailMessage.Body and would like to include CSS for formatting fonts, tables, etc. I am having a problem with the final HTML code being correctly generated.

For example:

public static void CreateMessageWithMultipleViews(string server, string recipients)
{
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage("jane@contoso.com","joe@contoso.com");

    // Construct body as HTML. 
    message.Body = @"<html>
        <head>
            <style>
                p{
                    font-family:""Trebuchet MS"", Arial, Helvetica, sans-serif;
                    font-size:0.9em;
                    text-align:left;
                }
            </style>
        </head>
            <body>
                Some body text
            </body>
        </html>");

    // Set this property so that HTML renders
    message.IsBodyHtml = true;

    // Send the message.
    SmtpClient client = new SmtpClient(server);
    client.Credentials = CredentialCache.DefaultNetworkCredentials;
try 
{
    client.Send(message);
}
catch (Exception ex) 
{
    Console.WriteLine("Exception caught: {0}", 
    ex.ToString() );
}

My mail recipients use Outlook 2010, and this displays exactly as expected. But I really like it - there are tags in the final email source <html>and <header>:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
    </head>
<html>
    <head>
        <style>
            [..truncated..]

So my question is: how to properly configure the source of HTML email messages using MailMessage so that it is well-formed? I can see the header property in the MailMessage class, but this concerns the message headers, not the HTML headers. Do I need to add CSS code somewhere else?

+4
1

, Outlook 2010, <html> <header> MailMessage :

message.Body = @"
        <style>
            <!--
            p{
                [truncating the rest...]
            }
            --->
        </style>";

Outlook, , , , ( ):

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=us-ascii"></head>
<style>
    [css...]
</style>
<body>
    [content...]
</body>
</html>

CSS , , HTML Outlook.

+2

All Articles