Formatting lost when editing the HtmlBody property of an Outlook item by using the Outlook object model

Original KB number:   4020759

Symptom

Assume that you create a new MailItem, AppointmentItem, or MeetingItem object by using the Outlook Object Model. You then set the HtmlBody property of the item to some previously created well-formed HTML source that contains Cascading Style Sheet (CSS) styles. After you call the Display method and the Send method to send the item, the formatting that's dictated by the configured CSS styles may disappear, or the paragraph styles may be replaced by the MSONormal class.

Cause

Microsoft Outlook uses Microsoft Word as its editor. Loss of formatting may occur when the HTML source is validated by the Word HTML engine when the item is sent.

Workaround

We recommend that you use the underlying WordEditor object of the inspector to edit the HTML and Rich Text Format (RTF) bodies of Outlook items when you use the Outlook Object Model, instead of editing the HtmlBody property. See the following example.

Note

See Word Object Model for more information.

using Outlook = Microsoft.Office.Interop.Outlook;
using Word = Microsoft.Office.Interop.Word;
namespace CreateAndEditMailItemUsingWord
{
    class Program
    {
        static void Main(string[] args)
        {
            Outlook.MailItem mailItem = (new Outlook.Application()).CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
            Word.Document wordDocument = mailItem.GetInspector.WordEditor as Word.Document;
            // Insert the text at the very beginning of the document
            // You can control fonts and formatting using the ParagraphFormat propety of the Word.Range object
            Word.Range wordRange = wordDocument.Range(0, 0);
            wordRange.Text = "Please insert your text here";
            mailItem.Display();
        }
    }
}