Perform Mail Merge in Word with Python: A Comprehensive Guide

Alice Yang
8 min readAug 16, 2024

--

Mail Merge in Word with Python
Mail Merge in Word with Python

Mail merge is a powerful feature in Microsoft Word that allows users to create personalized documents by combining a template with a data source. This is particularly useful for generating customized letters, labels, envelopes, and emails for individual recipients. In this guide, we’ll explore how to perform mail merge in Word using Python.

Overview

In this guide, we’ll cover the following topics:

Python Library for Performing Mail Merge in Word with Python

To perform mail merge in Word with Python, we’ll use the Spire.Doc for Python library. This library provides robust features for manipulating Word documents and executing mail merges programmatically.

You can install Spire.Doc for Python from PyPI by running the following command in your terminal:

pip install Spire.Doc

For more detailed information about the installation, you can check this official documentation: How to Install Spire.Doc for Python in VS Code.

Create a Mail Merge Template

A mail merge template is a pre-designed document used in the mail merge process to create personalized communications for multiple recipients. This template often contains static content that remains the same for all recipients, as well as placeholders, known as merge fields, that will be replaced with personalized information from a data source.

You can manually create a mail merge template using MS Word or automate this procedure with Python.

Create a Mail Merge Template in MS Word

Here are the steps to create a template with merge fields in MS Word:

  1. Create a Word document and open it.
  2. Click at the location where you want to insert static content.
  3. Enter your static content (text, images, etc.) as needed.
  4. Click at the location where you want to insert merge fields.
  5. Go to the Insert menu, select Quick Parts, and choose Field… from the drop-down list to open the Field dialog.
  6. In the Field names list, select MergeField.
  7. Enter a name for the merge field in the Field name text box and click OK.
Create Mail Merge Template in MS Word
Create Mail Merge Template in MS Word

Create a Mail Merge Template with Python

You can also automate the creation of a mail merge template using Python. Below is an example of how to create a mail merge template programmatically using Spire.Doc:

from spire.doc import *
from spire.doc.common import *

# Create a new document
template = Document()
# Add a section to the document
section = template.AddSection()
# Set the page margins for the section
section.PageSetup.Margins.All = 72 # 1 inch margins

# Add paragraphs with merge fields
paragraph1 = section.AddParagraph()
paragraph1.AppendField("CompanyName", FieldType.FieldMergeField)

paragraph2 = section.AddParagraph()
paragraph2.AppendField("CompanyAddress", FieldType.FieldMergeField)
# Start a new line
paragraph2.AppendBreak(BreakType.LineBreak)

# Add paragraphs with text and merge fields
paragraph3 = section.AddParagraph()
paragraph3.AppendText("Dear ")
paragraph3.AppendField("FirstName", FieldType.FieldMergeField)
paragraph3.AppendText(" ")
paragraph3.AppendField("LastName", FieldType.FieldMergeField)
paragraph3.AppendText(",")
paragraph3.AppendBreak(BreakType.LineBreak)

paragraph4 = section.AddParagraph()
paragraph4.AppendText("We are pleased to inform you about our upcoming conference. It will take place at the following location:")
paragraph4.AppendBreak(BreakType.LineBreak)
paragraph4.AppendText("Event Location: ")
paragraph4.AppendField("EventLocation", FieldType.FieldMergeField)
paragraph4.AppendBreak(BreakType.LineBreak)
paragraph4.AppendText("Event Date: ")
paragraph4.AppendField("EventDate", FieldType.FieldMergeField)
paragraph4.AppendBreak(BreakType.LineBreak)

paragraph5 = section.AddParagraph()
paragraph5.AppendText("Please confirm your attendance by replying to this email.")
paragraph5.AppendBreak(BreakType.LineBreak)

paragraph6 = section.AddParagraph()
paragraph6.AppendText("Sincerely,")
paragraph6.AppendBreak(BreakType.LineBreak)
paragraph6.AppendField("SenderName", FieldType.FieldMergeField)
paragraph6.AppendBreak(BreakType.LineBreak)
paragraph6.AppendField("SenderPosition", FieldType.FieldMergeField)

# Create a paragraph style
para_style = ParagraphStyle(template)
para_style.Name = "ParaStyle"
para_style.ParagraphFormat.LineSpacingRule = LineSpacingRule.Multiple
para_style.ParagraphFormat.LineSpacing = 12
para_style.CharacterFormat.FontName = "Arial"
para_style.CharacterFormat.FontSize = 12
template.Styles.Add(para_style)

# Apply the style to all paragraphs in the section
for i in range(section.Paragraphs.Count):
para = section.Paragraphs[i]
para.ApplyStyle(para_style.Name)

# Save the document as a .docx file
template.SaveToFile("MailMergeTemplate.docx", FileFormat.Docx2016)
# Or you can save the document in other Word formats like .doc
# template.SaveToFile("MailMergeTemplate.doc", FileFormat.Doc)

# Close the document
template.Close()
Create Word Mail Merge Template in Python
Create Word Mail Merge Template in Python

Perform Mail Merge in Word with Python

The Document.MailMerge.Execute() method in Spire.Doc for Python is used to populate merge fields in a mail merge template with data from a data source. This method requires two parameters:

  • fieldNames (List[str]): A list of the merge field names as they appear in the template.
  • fieldValues (List[str]): A list of values that will replace the merge fields in the template.

Steps to Perform a Mail Merge:

  1. Load the Mail Merge Template: Instantiate a Document class object and load the mail merge template.
  2. Define the Data Source: Prepare a dictionary with the specific details to be inserted into the template. The keys in the dictionary should match the names of the merge fields defined in your template.
  3. Execute Mail Merge: Use the Document.MailMerge.Execute() method to replace the merge fields in the template with the corresponding values from your data source.
  4. Save the Document: Save the finalized document with the merged data using the Document.SaveToFile() method.

Example

Here’s a simple example demonstrating how to use the Document.MailMerge.Execute() method to populate a mail merge template with data in Python:

from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
doc = Document()
# Load the mail merge template
doc.LoadFromFile("MailMergeTemplate.docx")

# Define the data source as a dictionary
# In the dictionary, the keys represent the names of the merge fields used in the mail merge template, and the values represent the corresponding data that will be inserted into those merge fields.
data_source = {
"CompanyName": "Global Solutions",
"CompanyAddress": "456 Oak Avenue",
"FirstName": "Mary",
"LastName": "Johnson",
"EventLocation": "City Hall",
"EventDate": "2024-09-20",
"SenderName": "Jane Smith",
"SenderPosition": "Director of Events"
}

# Replace the merge fields in the mail merge template with the corresponding values
doc.MailMerge.Execute(list(data_source.keys()), list(data_source.values())

# Save the merged document
doc.SaveToFile("output/MergedDocument.docx", FileFormat.Docx2016)
# Close the document
doc.Close()
Perform Mail Merge in Word with Python
Perform Mail Merge in Word with Python

Create Multiple Documents at Once Using Mail Merge in Word with Python

In the previous example, a single merged document was created from a mail merge template. When dealing with a large number of recipients, it’s often necessary to generate separate, individualized documents for each recipient. This allows you to tailor each document with specific details such as the recipient’s name, address, and other personal information.

Steps to Create Multiple Documents at Once Using Mail Merge:

  1. Load the Mail Merge Template: Instantiate a Document class object and load the mail merge template.
  2. Define the Data Source: Prepare a list of dictionaries where each dictionary contains the data for one recipient. The keys in the dictionaries should match the names of the merge fields defined in your template.
  3. Loop Through Data Source: For each dictionary in the data source:
  • Clone the Template: Create a copy of the mail merge template.
  • Execute Mail Merge: Replace the merge fields in the cloned document with the corresponding values from the dictionary.
  • Save the Document: Save the personalized document as a separate file.

Example

Here’s a simple example demonstrating how to create multiple documents at once using mail merge in Word with Python:

from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
doc = Document()
# Load the mail merge template
doc.LoadFromFile("MailMergeTemplate.docx")

# Define the data source as a list of dictionaries
# Each dictionary contains the data for one recipient
data_source = [
{
"CompanyName": "Acme Corporation",
"CompanyAddress": "123 Elm Street",
"FirstName": "John",
"LastName": "Doe",
"EventLocation": "Conference Center",
"EventDate": "2024-09-15",
"SenderName": "Jane Smith",
"SenderPosition": "Director of Events"
},
{
"CompanyName": "Global Solutions",
"CompanyAddress": "456 Oak Avenue",
"FirstName": "Mary",
"LastName": "Johnson",
"EventLocation": "City Hall",
"EventDate": "2024-09-20",
"SenderName": "Jane Smith",
"SenderPosition": "Director of Events"
},
{
"CompanyName": "Tech Innovators",
"CompanyAddress": "789 Pine Road",
"FirstName": "James",
"LastName": "Williams",
"EventLocation": "Community Center",
"EventDate": "2024-09-25",
"SenderName": "Jane Smith",
"SenderPosition": "Director of Events"
}
]

# Loop through the data source
for entry in data_source:
# Create a copy of the template
clone_doc = doc.Clone()

# Replace the merge fields in the copied document with the corresponding values
doc.MailMerge.Execute(list(entry.keys()), list(entry.values()))

# Save the copied document to a separate file
clone_doc.SaveToFile(f"output/Members/Member-{entry['FirstName']}_{entry['LastName']}.docx")

doc.Close()
Create Multiple Documents Using Mail Merge in Python
Create Multiple Documents Using Mail Merge in Python

Retrieve Merge Field Names in Word with Python

You can retrieve the names of merge groups and merge fields from a mail merge template with Spire.Doc.

Steps to Get Merge Field Names:

  1. Load the Mail Merge Template: Instantiate a Document class object and load the mail merge template.
  2. Retrieve Group Names: Get the names of merge groups.
  3. Retrieve Merge Field Names: Get merge field names within a specific group or get all merge field names within the template.

Example

Here’s a simple example demonstrating how to retrieve the names of merge groups and merge fields from a mail merge template with Python:

from spire.doc import *
from spire.doc.common import *

# Create a Document object and load the mail merge template
doc = Document()
doc.LoadFromFile("MailMergeTemplate.docx")

# Get the collection of group names
group_names = doc.MailMerge.GetMergeGroupNames()

# Get the collection of merge field names within a specific group such as "Products"
merge_field_names_within_group = doc.MailMerge.GetMergeFieldNames("Products")

# Get the collection of all merge field names
merge_field_names = doc.MailMerge.GetMergeFieldNames()

# Prepare content for output
content = []

# Append group names if not empty
if group_names:
content.append("-------------- Group Names ----------------------")
content.extend(group_names)

# Append merge field names within a specific group if not empty
if merge_field_names_within_group:
content.append("-------- Merge Field Names Within Specific Group ---------")
content.extend(merge_field_names_within_group)

# Append all merge field names if not empty
if merge_field_names:
content.append("---------- All Merge Field Names -----------------")
content.extend(merge_field_names)

# Write the contents to a TXT file
output_file = "output/merge_fields.txt"
with open(output_file, mode="w", encoding="utf-8") as f:
f.write("\n".join(content))
Get Mail Merge Field Names in Word with Python

Conclusion

This article demonstrated how to create a mail merge template and perform mail merge in Word using Python. In addition, it also explained how to retrieve merge field names from a mail merge template using Python. We hope you find it helpful.

Related Topics

--

--

Alice Yang

Skilled senior software developers with five years of experience in all phases of software development life cycle using .NET, Java and C++ languages.