Send Email (DOCX Body)
Sends emails using the content of a Word document (.docx) as the email body. Reads recipients from a CSV file.
Requirements
pip install python-docxSetup
Update the variables at the top of the script:
smtp_server = "smtp.example.com"
smtp_port = 587
username = "your-username"
password = "your-password"
from_address = "sender@example.com"
subject = "Your Subject"
docx_file_path = "path/to/your/document.docx"Usage
python send-email-import-docx-as-body.pyThe script reads each paragraph from the DOCX file and joins them as the email body, then sends to each recipient in the CSV.
Script
import smtplib
import csv
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from docx import Document #Requires pip3 install python-docx.
# SMTP server configuration
smtp_server = "SMTP Server"
smtp_port = 587 # For STARTTLS
username = "Username"
password = "Password"
# Email details
from_address = "from address"
subject = "Test Python Email 2"
docx_file_path = "path to docx" # Update this with your DOCX file path
to_address = "to address"
# Function to read DOCX content
def read_docx(file_path):
doc = Document(file_path)
full_text = []
for para in doc.paragraphs:
full_text.append(para.text)
return '\n'.join(full_text)
# Function to send email
def send_email(to_address, body):
# Create a multipart message
msg = MIMEMultipart()
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# Send the email
server.send_message(msg)
print(f"Email sent to {to_address}")
# Send the email
server.send_message(msg) # pyright: ignore[reportUndefinedVariable]
print(f"Email sent to {to_address}")
# Read the DOCX file
email_body = read_docx(docx_file_path)
send_email(to_address, email_body)
# Establish a secure connection with the SMTP server using STARTTLS
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
# Login to the SMTP server
server.login(username, password)
# Read email addresses from CSV file
with open('path to csv', 'r', newline='') as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
to_address = row[0] # Assuming email is in the first column
send_email(to_address, email_body)
# Close the connection
server.quit()Last updated on