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("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 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?