Chunking a distribution - israel-dryer/Outlook-Python-Tutorial GitHub Wiki

If you’re sending to a distribution of people that cannot be in a formal distribution list, you’re limited to 500 recipients per message. To get around this, you can break the distribution list into chunks of 500.

Getting started

Let's import the win32com library and dispatch an instance of Outlook. We'll also import csv to get our distribution.

import csv
import win32com.client as client

outlook = client.Dispatch('Outlook.Application')

Get your recipients

Suppose you have a csv file that contains the name and email addresses of a distribution of people... let's say there are 1,567 recipients.

with open('my_distro.csv', newline='') as f:
    reader = csv.reader(f)
    distro = [row for row in reader]  # (name, email)

Chunking the data

I now have a list of 1,567 recipients that I need to break into chunks of 500... since 500 is the max recipients on any email in Outlook.

# create empty chunk list
chunk_list = []

# increment in spans of 500, then append to chunk list
for x in range(0, len(distro), 500):
    chunk = distro[x:x+500]
    chunk_list.append(chunk)

Now that we have the chunks, or batches, we can send our messages.

for recipients in chunk_list:
    message = outlook.CreateItem(0)
    message.To = ";".join(recipients)
    message.Subject = "Missing time alert!"
    message.Body = "Please submit your time as soon as possible!"
    message.Send()

The recipients in the example above are lists of email addresses in a chunk. These email addresses are joined together with a semicolon using the str.join method.