Skip to content

Instantly share code, notes, and snippets.

@sehrishnaz
Last active February 1, 2022 19:01
Show Gist options
  • Save sehrishnaz/97a4543c07d227f6e8292a82f196fa70 to your computer and use it in GitHub Desktop.
Save sehrishnaz/97a4543c07d227f6e8292a82f196fa70 to your computer and use it in GitHub Desktop.
Send Bulk Email From Python Using Cloud Console Gmail API - Python Gmail Bot
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment