Wednesday, 17 October 2012

Inconsistent CSS styles applied to an email in Outlook when sending email from SharePoint

Recently I was working on a timer job that sends (html) emails via SharePoint's SPUtility.SendEmail function. The CSS styles I used in the email body were being inconsistently applied to the email when viewed in Outlook 2010. The method I was using was:

Create the email body, applying the styles at the top of the email body.
emailBody.Append(AddStyles());
emailBody.Append(body);

Send the email setting the fAppendHtmlTag parameter to true.
SPUtility.SendEmail(web, true, false, recipient, subject, emailBody)

To fix the issue, I set the fAppendHtmlTag parameter to false, instead adding the HTML tags myself, as such:
var body = String.Format("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=8\" /><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />{0}</head><body>{1}</body></html>", AddStyles(), emailBody);

Then send the email:
SPUtility.SendEmail(web, false, false, recipient, subject, body)

This worked nicely, and the CSS styles were now applied consistently throughout the body of the email.