Search Here

Send Bulk Email From Python Using Google Cloud Console Gmail API

In this article, you will learn how to create Gmail Bot to send bulk emails using a python script. This bot uses Google Cloud Console Gmail API to send emails in bulk.
Send Bulk Email From Python Using Cloud Console Gmail API

How Bulk Email Sender Bot Works

To send an email using python script follow the below steps.
  • Go to https://console.cloud.google.com/getting-started and create a new project
  • Under this project create a Gmail API library
  • Set and create OAuth Consent Screen, to do this you must use https://mail.google.com/
  • Add Test User for your app
  • Generate OAuth ClientId (this "token" is the key thing, and later we are going to use this JSON in our python bot)
  • Below is the complete video tutorial to do all of the above stuff steps by step.


  • You have to download the "client_secret.json" file. Remember you can use any name of json file but in this tutorial you must rename the downloaded json file as "credentials.json" and put that file into the directory where your python script exists
  • Create a folder named Gmail Python Bot, this directory contains following files.
    • Python script
    • Text file containing email on each line
    • An excel file that will contain email information. In our case in this file we have two columns. The first column contains the link of blog post and the second one have description of blog post.

This python bot reads an email from a text file and selects 20 emails randomly. It will also read from an excel file and collect email messages, in our case this will collect blog post descriptions and link randomly from an excel file and send an emails to the recipients after  every 12 to 15 minutes. 

Send Bulk Email From Python Using Cloud Console Gmail API

Below is the complete code to send email from python using google cloud console Gmail API.

import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from email.mime.text import MIMEText
import base64
import pandas as pd
import random
import time
import secrets
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://mail.google.com/']
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = ", ".join(to)
message['from'] = sender
message['subject'] = subject
msg_data = base64.urlsafe_b64encode(message.as_string().encode()).decode()
return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}
def send_message(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print('Message Id: %s' % message['id'])
return message
except Exception as error:
print(error)
if __name__ == '__main__':
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('gmail', 'v1', credentials=creds)
df_message = pd.read_excel("links_description.xlsx", sheet_name=0)
col_name = ['email']
df_email = pd.read_csv("email_file.txt", names=col_name)
sender = 'abc@gmail.com'
subject = 'Python and Odoo Development Tips'
post_after = [600, 720, 840, 900]
# post_after = [100,60]
for lp in range(df_message.shape[0]):
post = random.randint(0, df_message.shape[0] - 1)
email_message = df_message.description[post] + '\n' + df_message.link[post]
random_emails = random.sample(df_email.email.to_list(), 20)
# message = create_message(sender, random_emails, subject, email_message)
message = create_message(sender, random_emails, subject, email_message)
try:
send_message(service=service, user_id='me', message=message)
except Exception:
pass
print('*****sent to*****', random_emails)
print('*****message*****', email_message)
wait_sec = secrets.choice(post_after)
time.sleep(wait_sec)

Post a Comment

0 Comments