Skip to content

Instantly share code, notes, and snippets.

@iTrauco
Forked from azmirfakkri/send_email.py
Created January 26, 2023 02:11
Show Gist options
  • Save iTrauco/404e59efc3585593e779a6ba10df3119 to your computer and use it in GitHub Desktop.
Save iTrauco/404e59efc3585593e779a6ba10df3119 to your computer and use it in GitHub Desktop.
Email automation using Python and Google Sheet
# we need these modules to send the emails
import smtplib
import ssl
# these modules will allow you to create the client and interact
# with Google Sheet
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# these modules will help you create the HTML emails
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# create client using credentials downloaded from Google Cloud Platform
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('path/to/your/client_secret.json', scope)
client = gspread.authorize(credentials)
# specify the correct name of the Google Sheet
sheet = client.open('email-automation-test').sheet1
# Get all values in the Google Sheet
row_values_list = sheet.get_all_records()
# specify email and GMail App Password
from_email = '[email protected]'
password = 'YOUR GMAIL APP PASSWORD'
# iterate on every row of the Google Sheet
for row_value in row_values_list:
# we are dealing with dictionary, so you can use get method
name = row_value.get('name')
token = str(row_value.get('token'))
to_email = row_value.get('to_email')
# specify the path to your html email
html = ''.join(open('path/to/your/html').readlines())
# replace the variables with the values in the sheet
html = html.replace('${name}', name)
html = html.replace('${token}', token)
# set up from, to and subject
message = MIMEMultipart('alternative')
message['Subject'] = 'Token Reminder to Pet My Dogs'
message['From'] = from_email
message['To'] = to_email
# create MIMEText objects
part1 = MIMEText(html, 'html')
# attach the text/html part to the MIMEmultipart message
message.attach(part1)
# create a secure SSL context
context = ssl.create_default_context()
# log in and send the email
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:
server.login(from_email, password)
server.sendmail(from_email, to_email, message.as_string())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment