Last modified: Nov 12, 2025 By Alexander Williams
Email DOCX Files with Python
Automating document creation and distribution saves time. Python makes this easy. You can generate DOCX files and email them automatically.
This guide covers the complete process. We use python-docx for document generation. We use SMTP for email delivery.
Setting Up Required Libraries
First, install the necessary packages. You need python-docx for DOCX manipulation. You also need email and smtplib for sending emails.
pip install python-docx
Python's standard library includes email and smtplib. No extra installation is needed for these.
Creating a DOCX File with python-docx
Let's create a simple document. We'll add a title and some content. This demonstrates basic document generation.
from docx import Document
# Create a new document
doc = Document()
# Add a heading
doc.add_heading('Monthly Report', 0)
# Add a paragraph
doc.add_paragraph('This is the automated monthly report.')
doc.add_paragraph('Generated using python-docx.')
# Save the document
doc.save('monthly_report.docx')
The code creates a basic DOCX file. It includes a main heading and two paragraphs. The file saves as monthly_report.docx.
For more advanced formatting, check our Python docx Numbered Headings Guide. It helps with structured documents.
Configuring Email Settings
Next, configure your email settings. You need SMTP server details. This includes server address, port, and credentials.
# Email configuration
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "[email protected]"
sender_password = "your_app_password"
recipient_email = "[email protected]"
Use app passwords for Gmail. Regular passwords might not work. Other providers have similar security measures.
Creating the Email Message
Now, create the email message. We use Python's email.mime module. This handles attachments properly.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# Create message container
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = "Automated Monthly Report"
# Email body
body = "Please find the attached monthly report."
msg.attach(MIMEText(body, 'plain'))
The code sets up the basic email structure. It includes sender, recipient, subject, and body. The attachment comes next.
Attaching the DOCX File
Attaching the document requires specific handling. We read the file in binary mode. Then encode it for email transmission.
# Attach the DOCX file
filename = "monthly_report.docx"
with open(filename, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
'Content-Disposition',
f'attachment; filename= {filename}'
)
msg.attach(part)
This code reads the DOCX file as binary. It encodes it in base64. Then attaches it to the email message.
For generating different document types, see our Generate Certificates in DOCX with Python guide.
Sending the Email via SMTP
The final step is sending the email. We use smtplib to connect to the SMTP server. Then send the composed message.
import smtplib
# Send email
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, sender_password)
text = msg.as_string()
server.sendmail(sender_email, recipient_email, text)
server.quit()
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
Email sent successfully!
The code establishes a secure connection to the SMTP server. It authenticates using your credentials. Then sends the email with attachment.
Complete Working Example
Here's the complete code that combines all steps. This provides a ready-to-use solution for your projects.
from docx import Document
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# Create DOCX document
doc = Document()
doc.add_heading('Monthly Report', 0)
doc.add_paragraph('This is the automated monthly report.')
doc.add_paragraph('Generated and emailed using Python.')
doc.save('monthly_report.docx')
# Email configuration
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "[email protected]"
sender_password = "your_app_password"
recipient_email = "[email protected]"
# Create email message
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = "Automated Monthly Report"
body = "Please find the attached monthly report."
msg.attach(MIMEText(body, 'plain'))
# Attach document
filename = "monthly_report.docx"
with open(filename, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename= {filename}')
msg.attach(part)
# Send email
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, recipient_email, msg.as_string())
server.quit()
print("Email with DOCX attachment sent successfully!")
except Exception as e:
print(f"Error: {e}")
This complete script generates a document and emails it. You can customize it for your specific needs.
For template-based documents, our Python DOCX Templates with Jinja2 guide shows advanced techniques.
Common Issues and Solutions
Authentication errors are common. Make sure you're using app passwords for Gmail. Check your SMTP settings for other providers.
File not found errors can occur. Ensure the DOCX file exists in the correct path. The script should have read permissions.
SMTP connection issues might happen. Verify your internet connection. Check firewall settings blocking port 587.
Conclusion
Automating DOCX generation and emailing is powerful. Python makes it accessible and efficient. This workflow saves significant manual effort.
You can extend this for various use cases. Automated reports, certificates, or invoices. The possibilities are extensive.
Remember to handle credentials securely. Use environment variables for production. Test thoroughly before deployment.
This automation demonstrates Python's capability for document workflows. It combines file generation with communication channels effectively.