Send automated emails with python and the gmail api

Send automated emails with python and the gmail api

Sending emails programmatically with python and Gmail api is one of the best idea to consume our time and cost without any human interaction. In this tutorial I will show you how to send programmatically emails using python ang Gmail API.

I’m assuming that you are using GSuite and you have already verified your domain for GSuite and you have installed python latest version in your pc.

To send automated mail using Gmail and python there is some prerequisites you can find it below.

  1. Python 2.6 or greater
  2. The pip package management tool
  3. A google account with Gmail enabled
Sending emails with Gmail api service

This are common required stages: 

  1. Turn on Gmail API
  2. Install the google client library
  3. Initialize ezgmail
Step 1: Turn on Gmail API

Go to the following link Click Here to enable Gmail API in your account. And click the button Enable the Gmail API to get the credentials.json file. Store this file in the same folder/directory where you will store .py files.
Treat credentials.json as confidential.


Step 2: install the google client library

Run the following command from the website.

$ pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

You can copy-paste the command from the website.

Step 3: initialize ezgmail
Import ezgmail, os
Os.chdir(r’c:path ocredentials.json’)

Run this script once. It will open your browser to a google sign-in page. Enter your Gmail address and password. In the end you will get a token.json file.

Sending mail from Gmail

To send mail from Gmail follow the below script

Import ezgmail
recipient = ‘[email protected]
subject = ‘Test mail’
text = ‘Hi, How are you ?’
ezgmail.send(recipient, subject, text)
Reading unread mails from Gmail
import ezgmail
unreadThreads = ezgmail.unread()
# Get subject and date
result = ezgmail.summary(unreadthreads)
# Print the email
Search mail from Gmail
resultThread =‘finxter’)
result = ezgmail.summary(resultThread)
Download attachment from Gmail
Import ezgmail
threads =‘finxter’)

That’s all. If you find this article is helpful don’t forget to share with your friends. Please help us by doing comment using comment box. Thank you!

Also Read:

How to run multiple insert query in SQL using PHP in one go?

Post Comments(0)

Leave a reply