Sending Email with Python using Gmail API

vecteezy image

Preparing in Google Cloud Console,

For some api, we need to create api key to use their products and pass api key every time we request to their api. In the same way to use google api, we need to create some secret key. There are so many google api and we need to create a project and enable api that we want to use and create oauth client id as our secret key.

Create Project

Enable API

  • make sure your project is selected
  • go to navigation bar > APIs & Services > Library

Creating OAuth Consent Screen

  • go to navigation bar > APIs & Services > OAuth Consent Screen
  • create OAuth Consent Screen
  • add https://mail.google.com/ scope and update
add https://mail.google.com
  • add test user
  • check test user and scopes in summary section

Creating OAuth ClientId

  • go to navigation bar > APIs & Services > Credentials
  • create OAuth Client Id

Add to your project folder and rename credentials.json

Ready to use Gmail API

Send Email

from __future__ import print_function
import base64
import os.path
from email.mime.text import MIMEText
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

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://mail.google.com/']

creds = None
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)


def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
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)


message = create_message('me', john@gmail.com, 'hello', 'testing 123')
print(send_message(service=service, user_id='me', message=message))

you need to replace receiver email in create_message function

  • to authorize user, this will redirect to sign in with google
  • sign in and verify app

This message will send to john@gmail.com

--

--

--

Learning javascript and web-development

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

DevOps journey - a practitioner's insight

Meet our Audit Partners

Alibaba Cloud Series — EP 2: Comparing ECS Instance Types in Container Service for Kubernetes (ACK)

Things You Should Know Before Starting DynamoDB

BFS and DFS algorithms in Ruby

Hadoop 3.2.1. on Ubuntu 18.04 (Pseudo-Distribuited)

Make, Buy or SaaS?

Six Deployment Strategies

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cho Zin Thet

Cho Zin Thet

Learning javascript and web-development

More from Medium

Creating a django app in 5 mins!

How to Integrate SAWO SDK to your Vue code.

How to get the Fanatic badge easily on Stack Overflow the PRO way

Using Flask with MongoDB and SQLite database(33)