Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Properly Add CSS in a MailMessage

I'm writing some HTML to a MailMessage.Body and would like to include some CSS to format fonts, tables, etc. I'm having trouble getting the final HTML to be formed properly.

For example:

public static void CreateMessageWithMultipleViews(string server, string recipients)
{
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage("[email protected]","[email protected]");

    // 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 email recipients all use Outlook 2010 and this renders exactly as expected. But I have a hard time liking it -- there are repeated <html> and <header> tags in the final email source:

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

So my question is, how do I properly set the HTML source of an email using MailMessage so that it is well formed? I see a 'Header's property in the MailMessage class, but that is for the message headers, not HTML headers. Do I need to put the CSS code somewhere else possibly?

like image 373
tommy_o Avatar asked Oct 03 '22 09:10

tommy_o


1 Answers

Keeping in mind that I only need to render properly in Outlook 2010, I'm dropping the explicit <html> and <header> tags and allowing the MailMessage to handle those:

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

When I receive the email in Outlook, this is the format of the source, which works for rendering and it's quite as illogical as before (I corrected the indention for readability):

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

The CSS still isn't contained within the tag, but at this point I feel lucky that the HTML renders properly in the Outlook client.

like image 54
tommy_o Avatar answered Oct 13 '22 11:10

tommy_o