Overview: Python Bulk Email Sender
Let’s get started with Python Bulk Email Sender Using Gmail & Google Sheets. From Google Sheets API to Setup Gmail SMTP Server, will take a quick look at each step of sending emails using Python.
What’s Next? – Python Bulk Email Sender
In this article, let’s explore behind the scenes how we can use Python to send bulk emails by taking the recipients from Google Spreadsheet. Starting with authenticating the program with Google SMTP server to Sending Emails, will cover each step. So, let me guide you through the whole process of sending the bulk emails using Python.
Prerequisite Article: Python Bulk Email Automation using Gmail
Table of Contents
Watch Video Explanation
Proceed the below steps first before jumping to the coding part!
Question: How to enable Google Sheet & Drive API?
- Go to Google Cloud Console:
- Open Google Cloud Console.
- Click on Select a Project → Create a new project (if not already created).
- Enable Google Sheets API & Google Drive API:
- In the APIs & Services section, click on Enable APIs and Services.
- Search for Google Sheets API and enable it.
- Search for Google Drive API and enable it (needed for access).
Question: How to Get “your_credentials.json” for Google Sheets API?
Create Service Account Credentials:
- In the APIs & Services → Credentials tab, click Create Credentials → Service Account.
- Give it a name (e.g., Bulk Email Sender).
- Click Done (no need to assign additional roles).
Generate JSON Key File:
- Click on the newly created Service Account.
- Go to the Keys tab → Click Add Key → Select JSON.
- This will download a JSON file (e.g., your_credentials.json).
Move the JSON File to Your Python Project Folder:
- Place the downloaded JSON file in the same directory as your Python script.
- Rename the file name and make it something easy to read like my-project-key.json. Optional.
Share Your Google Sheet with the Service Account:
- Open your Google Sheet.
- Enter the recipient’s email address, but from column 1 and row 1. Do not give any header name to the column.
- Click the Share button (top-right corner).
- Copy the email address from the JSON file (under “client_email”).
- Paste it in the Share field of Google Spreadsheet and give Editor access.
Question: Write a Python program to send bulk emails using Google Spreadsheet and Gmail.
#Install required modules & libraries
#Connect to Gmail's SMTP Server
import smtplib
#Access to Google Spreadsheet
import gspread
#Authorize Python program securly with Google API
from oauth2client.service_account import ServiceAccountCredentials
# Add features to email -- subject, email body, attachment
from email.mime.multipart import MIMEMultipart
#Set the email format -- plain or HTML
from email.mime.text import MIMEText
Explanation:
To install library or module enter the following code in the terminal:
pip install smtplib email
- The smtplib is a Python module to connect with Gmail’s SMTP live server.
- The gspread is a Python library to manage and work with Google Spreadsheet.
- The oauth2client is a Python library to authenticate and verify the details to connect with SMTP server.
- The email module is a Python package to handle the emails.
- The MIMEMultipart is a library which adds additional features to email like: subject, body, attachment, etc.
- The MIMEText decides the email format: Plain or HTML (bold, italic, headings, etc.).
#Setup Google Sheets API
def get_recipients(sheet_name, column_index=0):
#Define API Access
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
#Get login details Using Service Account
creds = ServiceAccountCredentials.from_json_keyfile_name("my-project-key.json", scope)
Explanation: Start with creating function get_recipients passed two parameters sheet_name, which stores the Google Spreadsheet name and column_index=0, default value is 0 because Python indexing number start from 0.
The scope variable stores the API links for Google Spreadsheet & Drive, needed for the authentication.
Using the ServiceAccountCredentials library with from_json_keyfile_name method, loaded the service account login details from the json file downloaded and authenticated the details.
#Authorize Google Sheets API
client = gspread.authorize(creds)
Explanation: Since recipient emails are stored in a Google Sheet, therefore, we need the gspread library to open the Google Sheet to read email addresses from a specific column to fetch data dynamically.
#Open the Google Sheet
sheet = client.open(sheet_name).sheet1
# Read email column (0-based index)
recipients = sheet.col_values(column_index+1)
Explanation: The open method is used to open the Google Spreadsheet and property sheet1 is used to access the first sheet in the Google Worksheet.
Note: Open the Google Spreadsheet before running the program. The method col_values access the recipient emails. +1 is used because in Google Spreadsheet cells counting starts from 1.
return [email.strip() for email in recipients if email.strip()]
Explanation: for loop is used to access each email one by one. strip() method is used to remove any whitespace and skip any blank row (if any) among email addresses in Google Spreadsheet.
# Gmail credentials
SENDER_EMAIL = "your_email@gmail.com"
SENDER_PASSWORD = "your_App_password"
# List of recipients
recipients = ["recipient1@example.com", "recipient2@example.com", "recipient3@example.com"]
# Email subject and body
subject = "Bulk Email Test"
body = "Hello,This is a test email sent using Python."
Steps to create App Password:
- Login to gmail account
- Go to Account manage option
- Go to under Security option
- Security > enable 2 step verification (mandatory)
- In search section, search App Password
- App Password > enter the app name > get the App Password from Gmail.
try:
#Gmail SMTP Path and Port no.
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls() # Secure connection
server.login(SENDER_EMAIL, SENDER_PASSWORD)
Explanation: The SMTP establishes the local host to the system to connect with Gmail’s server. The login method is used to log into the server with login details.
for recipient in recipients:
msg = MIMEMultipart()
msg["From"] = SENDER_EMAIL
msg["To"] = recipient
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))
Explanation: The for loop is used to access each email address one by one. The attach method is used to attach all email features to the main email body.
#Send email
server.sendmail(SENDER_EMAIL, recipient, msg.as_string())
print(f"Email sent to {recipient}")
Explanation: The sendmail method is used to start the whole process of sending the emails to the recipients.
server.quit()
print("All emails sent successfully!")
Explanation: The quit() method is used to disconnect from the SMTP server after sending all emails successfully.
except Exception as e:
print(f"Error: {e}")
Explanation: The except clause is used to handle the error if found any error in the try clause. try clause let’s test the code for error while except clause raises an exception and handles the error.
Complete Code:
import smtplib
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Step 1: Setup Google Sheets API
def get_recipients_from_gsheet(sheet_name, column_index=0):
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("your_credentials.json", scope)
client = gspread.authorize(creds)
sheet = client.open(sheet_name).sheet1 # Open the first sheet
recipients = sheet.col_values(column_index + 1) # Read email column (0-based index)
return [email.strip() for email in recipients if email.strip()]
# Gmail credentials
SENDER_EMAIL = "your_email@gmail.com"
SENDER_PASSWORD = "your_password_or_app_password"
# Fetch recipients from Google Sheets
SHEET_NAME = "Your Google Sheet Name"
recipients = get_recipients_from_gsheet(SHEET_NAME)
# Email subject and body
subject = "Bulk Email Test"
body = "Hello, This is a test email sent using Python."
# Step 2: Sending Emails
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(SENDER_EMAIL, SENDER_PASSWORD)
for recipient in recipients:
msg = MIMEMultipart()
msg["From"] = SENDER_EMAIL
msg["To"] = recipient
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))
server.sendmail(SENDER_EMAIL, recipient, msg.as_string())
print(f"Email sent to {recipient}")
server.quit()
print("All emails sent successfully!")
except Exception as e:
print(f"Error: {e}")
Now it’s YOUR turn!
Let’s share your wonderful experience of sending bulk emails using Python with Gmail. What replies did you get from recipients funny or surprising? Don’t forget to leave a comment to YouTube Video: Python Beginner Project: Python Bulk Email Sender Using Gmail & Google Sheets.
Conclusion: Python Bulk Email Sender
Automating bulk emails with Google Spreadsheet using Python and Gmail streamlines communication, making it faster and more efficient. Using SMTP for sending emails allows you to automate email campaigns, newsletters, or notifications with just a few lines of code.
This project not only saves time but also eliminates manual errors, ensuring smooth and reliable email delivery. Whether you’re a business professional or a developer, Python bulk email automation is a powerful tool to enhance productivity.