VBA Outlook: Format e-mail as html

VBA - Visual Basic for Application

Anyone who does a lot of programming with the VBA editor in order to write a few macros that automate recurring tasks will quickly come into contact with the MailItem.

The MailItem represents the object of the respective e-mail in the code editor. You can assign various properties to it. For example, you can mark selected e-mails as read with a VBA macro or write an automatic reply to an e-mail. One would then also like to assign the correct formatting, e.g. HTML, to such an automatic reply e-mail, as HTML offers considerably more design options than a pure text e-mail.

Use BodyFormat property

To achieve HTML formatting, one must use the BodyFormat property, as shown in the following image and code example.

Screenshot VBA source code to format a MailItem as HTML mail
Assign the HTML format to BodyFormat property
Sub ReplyMSG()
    Dim olItem As Outlook.MailItem
    Dim olReply As MailItem
    
    For Each olItem In Application.ActiveExplorer.Selection
        Set olReply = olItem.Reply
        olReply.BodyFormat = olFormatHTML
        '...more code here
    Next olItem
End Sub

In the sample code, reply mails are generated for all emails marked in the inbox and each MailItem of the reply mail is assigned the html format via the BodyFormat property (olFormatHTML).

BodyFormat is an enumeration, which means that you can also simply assign the appropriate numerical value. Besides olFormatHTML there are the following:

    • olFormatUnspecified (value 0): no specific formatting
    • olFormatPlain (value 1): the mail object is formatted as text-only
    • olFormatHTML (value 2): Mail is formatted as HTML
    • olFormatRichText (value 3): Mail is output in rich text format, which also offers design options like html.

Note:

In order for the code execution to work properly in Outlook, the following must be set under “Tools” ➤ “References” the correct libraries must be selected.

Screenshot of the necessary references in the VBA editor
Set the required library under Tools ➤ References

Now you can continue working with olReply and assign text in the form of HTML code, for example.

Leave a Reply

Your email address will not be published. Required fields are marked *