Python to Send Emails from CSV File with Full Source Code For Beginners

This project contains a simple bulk email script that sends the same message to a list of recipients.

Dependencies:

This project only requires the Python standard library (more specifically, the csvemail, and smtplib modules).

Running the script:

The script requires two configuration files:

  • emails.csv should contain the email addresses to send the message to.
  • credentials.txt should contain your SMTP server login credentials, with your user name and your password on sepate lines, with no additional whitespace or other decorations.

The project’s directory contains two example files that you’ll probably both want and need to edit.

Once you have these files set up, simply

python Send_emails.py
Code language: CSS (css)

Development ideas:

  • A proper email sender would use Cc: or Bcc: and send the same message just once.
  • Don’t play frivolously with this; your email provider, and/or the recipient’s, may have automatic filters which quickly block anyone who sends multiple identical messages.
  • The script simply hardcodes the conventions for Gmail.com. Other providers may use a different port number and authentication regime.

Source Code:

Sending_mail.py

import csv from email.message import EmailMessage import smtplib def get_credentials(filepath): with open("credentials.txt", "r") as f: email_address = f.readline() email_pass = f.readline() return (email_address, email_pass) def login(email_address, email_pass, s): s.ehlo() # start TLS for security s.starttls() s.ehlo() # Authentication s.login(email_address, email_pass) print("login") def send_mail(): s = smtplib.SMTP("smtp.gmail.com", 587) email_address, email_pass = get_credentials("./credentials.txt") login(email_address, email_pass, s) # message to be sent subject = "Welcome to Python" body = """Python is an interpreted, high-level, general-purpose programming language.\n Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability\n with its notable use of significant whitespace""" message = EmailMessage() message.set_content(body) message['Subject'] = subject with open("emails.csv", newline="") as csvfile: spamreader = csv.reader(csvfile, delimiter=" ", quotechar="|") for email in spamreader: s.send_message(email_address, email[0], message) print("Send To " + email[0]) # terminating the session s.quit() print("sent") if __name__ == "__main__": send_mail()
Code language: PHP (php)

credentials.txt

YourEmail Yourpass

emails.csv

abc@123.com def@123.com xyz@123.com
Code language: CSS (css)

Leave a Comment