This Python script allows you to send personalized emails with attachments in bulk using data from an Excel file. Each recipient gets a customized message and file attachment.
It’s suitable for workshops, events, certificates, reports, or general mailings.
Before running the script, make sure you have:
-
Python 3 installed
-
Python libraries:
pandas,smtplib,email,pathlibInstall pandas if needed:pip install pandas
-
A Gmail account with 2-Step Verification enabled (needed for App Passwords)
-
Open your Google Account: https://myaccount.google.com
-
Go to Security → 2-Step Verification and enable it.
-
Under Security, click App passwords.
-
Select:
- App → Mail
- Device → Other (e.g., “Python script”)
-
Click Generate and copy the 16-character App Password.
-
Use this App Password in your script instead of your normal Gmail password.
-
SMTP is the protocol used to send emails programmatically.
-
For Gmail:
- SMTP server:
smtp.gmail.com - TLS port:
587
- SMTP server:
-
TLS encrypts your email during sending to ensure security.
The script reads an Excel file with recipient data. Your Excel file should have the following columns:
| Column Name | Description | Example |
|---|---|---|
Name |
Recipient’s name | John Doe |
Mail |
Recipient’s email address | john@example.com |
Path |
Full path to the file you want to attach | C:\Users\John\Documents\report.pdf |
- Column names must match exactly (case-sensitive).
Pathshould include the full filename and extension.- Example Excel file:
recipients.xlsx
Open the Python script and replace placeholders:
-
Excel file path
excel_file_path = 'recipients.xlsx' # path to your Excel file
-
Sender email and App Password
sender_email = 'YOUR_EMAIL_HERE' sender_password = 'YOUR_APP_PASSWORD_HERE'
-
SMTP server and port
smtp_server = 'smtp.gmail.com' smtp_port = 587
-
Email subject and body
- Customize
msg['Subject']andbody. - The script automatically includes each recipient’s name.
- Customize
- Reads the Excel file and iterates over all rows.
- Checks that the attachment file exists.
- Creates a personalized email for each recipient.
- Attaches the file.
- Sends the email via Gmail SMTP.
- Prints logs for sent or skipped emails.
- Closes the SMTP connection after sending all emails.
- Always test with 1-2 emails before sending to everyone.
- Make sure all attachment files exist at the specified paths.
- Avoid sending too many emails at once; Gmail may block or limit your account.
- Never share your real Gmail password; use an App Password.
-
Add a delay between sending emails to avoid Gmail rate limits:
import time time.sleep(2) # 2-second delay between emails
-
Use HTML emails for better formatting.
-
Log sent or failed emails to a CSV for tracking.
-
Make the script reusable for multiple types of emails by adding a column like “Category” in Excel.