Python mail merge

Python provides several libraries to perform mail merge, which is the process of combining a template with data to create multiple documents. Here are a few options:

  1. DocxTemplate: This library allows you to create and modify Microsoft Word (.docx) files using Python. You can use it to perform mail merge by replacing placeholders in a template with data.

Example:

import docx
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH

# Create a new document
doc = Document()

# Add a paragraph to the document
p = doc.add_paragraph("Hello, ")

# Add a placeholder for the name
p.add_run("[Name]")

# Save the document to a file
doc.save("template.docx")

# Load the template
template = docx.Document("template.docx")

# Replace the placeholder with the name
template.paragraphs[0].text = "Hello, John"

# Save the merged document to a file
template.save("merged.docx")
  1. MailMerge: This library provides a simple way to perform mail merge using Python. It supports various file formats, including Word (.docx), Excel (.xlsx), and PDF.

Example:

import mailmerge

# Create a new mail merge object
mm = mailmerge.MailMerge()

# Set the template file
mm.set_template_file("template.docx")

# Set the data file
mm.set_data_file("data.csv")

# Perform the mail merge
mm.merge()

# Save the merged documents to a file
mm.save("merged.docx")
  1. python-docx-merge: This library provides a simple way to merge data with a Word (.docx) template using Python.

Example:

import docx_merge

# Create a new merge object
merge = docx_merge.Merge()

# Set the template file
merge.set_template_file("template.docx")

# Set the data file
merge.set_data_file("data.csv")

# Perform the merge
merge.merge()

# Save the merged document to a file
merge.save("merged.docx")
  1. OpenPyXL: This library provides a way to read and write Excel (.xlsx) files using Python. You can use it to perform mail merge by replacing placeholders in a template with data.

Example:

import openpyxl

# Load the template file
wb = openpyxl.load_workbook("template.xlsx")

# Select the first sheet
sheet = wb.active

# Replace the placeholder with the name
sheet["A1"] = "Hello, John"

# Save the merged file to a file
wb.save("merged.xlsx")

These libraries provide a range of features and options for performing mail merge in Python. You can choose the one that best fits your needs and requirements.