Python: Create and Execute Conditional Mail Merges in Word Documents

Conditional mail merge in Word documents is a powerful method for personalized communication at scale. Unlike other mail merges that apply the same template to all recipients, conditional mail merge allows users to customize content based on specific criteria or conditions, ensuring that each recipient receives information that is directly relevant to them. By leveraging Python, users can automate the creation and execution of conditional mail merges.

This article will show how to create and execute conditional mail merges in Word documents through Python code using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to: How to Install Spire.Doc for Python on Windows

Create Conditional Mail Merge in a Word Document with Python

A conditional mail merge uses an If field containing a mail merge field, which alters the merge results based on the data. To add a conditional mail merge to a Word document, insert an If field, then include a mail merge field within the If field’s code, and finish by adding the field end mark to complete the setup. The condition is controlled by the code within the If field.

The detailed steps for adding a conditional mail merge to a Word document are as follows:

  • Create an instance of the Document class to generate a Word document.
  • Add a section to the document and configure the page setup.
  • Create paragraph styles, add paragraphs, and set their formats.
  • Create an IfField object, set its starting code through the IfField.Code property, and insert it into a paragraph using the Paragraph.Items.Add() method.
  • Append a mail merge field to the paragraph using the Paragraph.AppendField() method.
  • Append the remaining code to the paragraph using the Paragraph.AppendText() method.
  • Append a field end mark to end the If field using the Paragraph.AppendFieldMark() method.
  • Set the end mark as the end mark of the If field through the IfField.End property.
  • Save the document using the Document.SaveToFile() method.
  • Python
from spire.doc import *

# Create an instance of Document
doc = Document()

# Add a section to the document
section = doc.AddSection()

# Set the page size and margins
section.PageSetup.PageSize = PageSize.A4()
section.PageSetup.Margins.All = 50

# Create a paragraph style
style = ParagraphStyle(doc)
style.Name = "Style1"
style.CharacterFormat.FontName = "Arial"
style.CharacterFormat.FontSize = 14
style.ParagraphFormat.BeforeSpacing = 5
style.ParagraphFormat.AfterSpacing = 10
doc.Styles.Add(style)

# Add paragraphs and set the style
paragraph = section.AddParagraph()
paragraph.AppendText("Dear ")
paragraph.AppendField("FirstName", FieldType.FieldMergeField)
paragraph.AppendText(" ")
paragraph.AppendField("LastName", FieldType.FieldMergeField)
paragraph.AppendText(",")
paragraph.ApplyStyle(style.Name)
paragraph = section.AddParagraph()
paragraph.AppendText("\r\nThank you for being a valued customer. We appreciate your business and support.")
paragraph.ApplyStyle(style.Name)

# Add an If field to a paragraph
paragraph = section.AddParagraph()
ifField = IfField(doc)
ifField.Type = FieldType.FieldIf
ifField.Code = "IF "
paragraph.Items.Add(ifField)
# Add a mail merge field in the code of the If field
paragraph.AppendField("CustomerType", FieldType.FieldMergeField)
paragraph.AppendText(" = ")
paragraph.AppendText("\"VIP\"")
paragraph.AppendText(" \"As a VIP customer, we have a special offer just for you! Enjoy a 20% discount on your next "
                     "purchase.\"")
paragraph.AppendText("\"We appreciate you choosing us! Please keep an eye out for our future special offers and "
                     "discounts.\"")
# Add a field end mark at the end to end the If field
endIf = paragraph.AppendFieldMark(FieldMarkType.FieldEnd)
ifField.End = endIf
paragraph.ApplyStyle(style.Name)

# Add paragraphs and set the style
paragraph = section.AddParagraph()
paragraph.AppendText("Your total spending with us is ")
paragraph.AppendField("TotalSpent", FieldType.FieldMergeField)
paragraph.ApplyStyle(style.Name)
paragraph = section.AddParagraph()
paragraph.AppendText("\r\nBest regards,\r\nTech Inc.")
paragraph.ApplyStyle(style.Name)

# Save the document
doc.SaveToFile("output/ConditionalMailMerge.docx", FileFormat.Docx)
doc.Close()

Python: Create and Execute Conditional Mail Merges in Word Documents

Execute Conditional Mail Merge in a Word Document with Python

The Document.MailMerge.Execute(fieldNames: list[str], fieldValues: list[str]) method provided by Spire.Doc for Python allows for mail merge operations within Word documents. After the merge, you can update the results of conditional mail merges by setting the Document.IsUpdateFields property to True. The detailed steps are as follows:

  • Read the data in the table used for the merge as a two-dimensional list.
  • Iterate through the data rows, skipping the header:
    • Create an instance of the Document class and load the Word document to be merged.
    • Get the names of the mail merge fields as a list using the Document.MailMerge.GetMergeFieldNames() method.
    • Execute the mail merge with the data using the Document.MailMerge.Execute() method.
    • Update the If field by setting the Document.IsUpdateFields property to True.
    • Save the document using the Document.SaveToFile() method.
  • Python
from spire.doc import *
import csv

# Read the data from a CSV file
data = []
with open("Customers.csv", "r") as csvfile:
    read = csv.reader(csvfile)
    for row in read:
        data.append(row)

# Iterate through the data rows by skipping the header
for i in range(1, len(data)):
    # Create an instance of Document and load a Word document
    doc = Document("output/ConditionalMailMerge.docx")
    # Get the field names from the document
    fieldNames = doc.MailMerge.GetMergeFieldNames()
    # Execute the mail merge
    doc.MailMerge.Execute(fieldNames, data[i])
    # Update the If field
    doc.IsUpdateFields = True
    # Save the document
    doc.SaveToFile(f"output/Customers/{data[i][0]} {data[i][1]}.docx", FileFormat.Docx2019)

doc.Close()

Python: Create and Execute Conditional Mail Merges in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.