Automating emails through Gmail API and Python
Emails play an important role for a business. Besides normal communication, businesses use email for several other reasons, such as collecting customer feedback, surveys, log reports, sales notifications, Google Alerts etc. and also forwarding them to other applications such as Slack, IoT applications or any ITTT application.
Imagine having a system wherein — when you receive an email, a bot checks for the subject of the email, and takes corrective action automatically. E.g. a bot scans through your inbox and:
- Updates all the sales notifications into your accounting database
- Updates all the customer queries into your CRM
- Updates emails from a specific sender to your high-priority to-do list
While several different plugins and apps are available for these tasks, they include a risk of using and sharing your data, and also come for a price. However, you can do all the stuff in-house by writing simple scripts and using Gmail-API.
I have been using the Gmail and other Google APIs for quite some time, and have found them to be very convenient and useful – though I personally find Gmail API to be a bit confusing for beginners. The API’s wizard comes handy to create the project, get credentials, and authenticate them. However, the process that should be followed after that is not mentioned clearly.
Therefore, I have created a sample Python (3.5) script that does the following simple tasks:
- Go to Gmail inbox
- Find and read all the unread messages
- Extract details (Date, Sender, Subject, Snippet, Body) and export them to a .csv file / DB
- Mark the messages as Read - so that they are not read again
Please check for the script at my GitHub
Before running this script, the user should get the authentication by following
the Gmail API link. Also, client_secret.json should be saved in the same directory as this file
The script outputs a dictionary in the following format:
{
'Sender': '"email.com" <name@email.com>',
'Subject': 'Lorem ipsum dolor sit ametLorem ipsum dolor sit amet',
'Date': 'yyyy-mm-dd',
'Snippet': 'Lorem ipsum dolor sit amet'
'Message_body': 'Lorem ipsum dolor sit amet'
}
The dictionary can further be exported as a .csv or into a database and used for anything, by a slight customization. E.g. you can set your website’s contact form in a way that the mail comes to you with a specific subject. You can, then, add a new snippet with a simple ‘if-then-else’ condition to filter all the mails with that subject and forward them to your CRM.
Please let me know if you need additional help or have any queries.
I was googling on how to do the exact same thing....and look where I reached........
Hi Abhishek, it would be great to connect and speak on this. I'm on Mahdi dot Shariff AT gmail dot com