Send Email (CSV Import)
Sends the same email to multiple recipients read from a CSV file.
Setup
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"
body = "Your email body"CSV Format
The CSV should contain email addresses in the first column:
recipient1@example.com
recipient2@example.com
recipient3@example.comUsage
python send-email-csvimport.pyUpdate the CSV file path in the script before running.
Script
import smtplib
import csv
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# SMTP server configuration
smtp_server = "SMTP Server"
smtp_port = 587 # For STARTTLS
username = "Username"
password = "Password"
# Email details
from_address = "address"
subject = "Test Python Email 2"
body = "This is a Test Email sent via Python script"
to_address = "to address"
# Function to send email
def send_email(to_address):
# 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}")
# 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') 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)
# Close the connection
server.quit()Last updated on