HTML formatted email - israel-dryer/Outlook-Python-Tutorial GitHub Wiki

Plain text is nice, but using HTML formatting in your email can dramatically improve the look-and-feel of the email. Fortunately, out of everything we've covered so far, only one thing will change, and that is using the HTMLBody property instead of the Body property.

Getting started

Let's go ahead and start with a basic Happy Birthday email using what we learned from the last lesson.

Setting the plain-text body will prevent the auto-signature from applying to the message, which is also a nice bonus if you don't want it in your message. You could also set the body to an empty string to achieve the same result.

import win32com.client as client

outlook = client.Dispatch('Outlook.Application')
message = outlook.CreateItem(0)
message.To = '[email protected]'
message.CC = '[email protected]'
message.BCC = '[email protected]'

message.Subject = 'Happy Birthday"'

HTML Formatting

Next, let's insert a very simple HTML formatted string into the HTMLBody property.

message.HTMLBody = '<span> Wishing you a very happy birthday!! </span>'

Let's spice it up with a birthday cake image.

html_body = """
    <div>
        <h1 style="font-family: 'Lucida Handwriting'; font-size: 56; font-weight: bold; color: #9eac9c;">
            Happy Birthday!! 
        </h1>
        <span style="font-family: 'Lucida Sans'; font-size: 28; color: #8d395c;">
            Wishing you all the best on your birthday!!
        </span>
    </div><br>
    <div>
        <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/cute-birthday-instagram-captions-1584723902.jpg" width=50%>
    </div>
    """

message.HTMLBody = html_body

What you should see now is something very much like the example below


Happy Birthday!!

Wishing you all the best on your birthday!!


You can now send the message using the Send method that you learned in the last lesson.

message.Send()
⚠️ **GitHub.com Fallback** ⚠️