How to Mail Merge with Python

If you don’t have Microsoft Outlook, there are loads of Gmail add-ons you can use for mail merge. In fact there are so many that a popular one is called Yet Another Mail Merge.

But they typically have a learning curve. And it looks like a lot of them require some kind of Chrome extension or some other gobbledygook to get it to work.

I don’t want to spend time figuring out how to use someone else’s software when I know I can do it on my own in about as much time.

Let’s break mail merge down into its component parts…

  • a text document (or email body) which is populated with data from a
  • CSV or Excel file (or a database if ya want)
  • an email, sent for each row of the above data, with content populated by the data

Those are all things you can code up on your own with Python efficiently, especially if you lean on a couple of libraries.

Email Body

To craft your messaging, use a triple-quote string so that spacing will be preserved. Each part that will be populated by data can be replaced with a “{}” (i.e. curly brackets). You’ll use Python’s string.format() method to fill in the fields from the dataset.

Data Fields

You can import the csv library to and use it to pull your data fields from a .csv file, like so:

Simple Mail Transfer Protocol (SMTP)

For this, you’ll need to import smtp. This uses your own Gmail account, and sends an email from it to the specified recipient, with subject and body specified. You will probably need to adjust the setting in your Gmail account to allow less secure apps to access it.

For each row in your data, you can use a function like this:

Put It All Together!

The full code would look something like this. I’ve modularized the CSV function and the mailer function into two separate Python files, named CSV_actions and mailer1, respectively, since I use them in other programs.

That’s it! A super simple mail merge, with no fees or sign-ups needed.

Leave a Reply
