Email templates - israel-dryer/Outlook-Python-Tutorial GitHub Wiki

You've learned how to create plain-text and HTML formatted emails. Another tool that comes in handy is an email template. This is especially true if you plan on sending emails in batches, or you want to customize an email for each recipient.

Getting started

Let's use everything from the prior example, except with one change... we're going to insert a {} into the HTML string so that we can using string formatting to insert custom text into the message... in this case the custom text will be the recipient's name.

import win32com.client as client

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

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"'
message.Body = ""

Customizing a message

To use the template, you simply pass in a variable with string formatting

message.HTMLBody = html_body.format('Bob')

You should now see the name "Bob" in the message or whatever name you passed as an argument in your string formatting.

Try replacing "Bob" with any number of other names that you can think of

message.HTMLBody = html_body.format('Richard')
message.HTMLBody = html_body.format('Ariana')
message.HTMLBody = html_body.format('Alister')
message.HTMLBody = html_body.format('Priyanka')

Imagine that you are iterating over a list of recipients and email addresses... you can create a custom email for each person by simply changing the value or variable you pass with string formatting. This works with plain-text message too.

This is a very handy tool to have when you need to send mail in bulk.

⚠️ **GitHub.com Fallback** ⚠️