Mastering Your Gmail Inbox With Python

Eric Christenson
5 min readApr 16, 2023

--

Photo by Thought Catalog on Unsplash

Introduction

Email has become an essential part of our daily lives, both for personal and professional communication. With the volume of emails we receive daily, managing and organizing our inboxes can be an overwhelming task. Gmail, one of the most popular email platforms, provides users with a plethora of tools and features to help organize and manage their inboxes. However, sometimes these built-in tools might not be enough, especially for those who need a higher level of customization and automation. That’s where Python comes in!

Python is an easy-to-learn, versatile programming language that can interact with various platforms and services, including Gmail. In this article, we will explore different ways to leverage Python to manage and organize your Gmail inbox more efficiently, automate repetitive tasks, and ultimately save you time.

Table of Contents:

  1. Setting Up Your Environment
  2. Connecting to Gmail Using the Gmail API
  3. Reading and Filtering Emails
  4. Sorting and Organizing Emails
  5. Automating Email Responses
  6. Scheduling Email Reminders
  7. Conclusion

Setting Up Your Environment

To get started, you will need to set up your Python environment and install the necessary libraries. We will be using Python 3.6 or higher, the Google APIs Client Library for Python, and some additional Python packages.

Step 1: Install Python

If you don’t have Python installed on your system, download and install Python from the official website: https://www.python.org/downloads/

Step 2: Install Google APIs Client Library for Python

To interact with the Gmail API, you will need the Google APIs Client Library for Python. Install it using pip:

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

Step 3: Install Additional Python Packages

We will also need some additional Python packages. Install them using pip:

pip install dateparser

Connecting to Gmail Using the Gmail API

Before interacting with the Gmail API, you will need to create a Google Cloud Platform (GCP) project, enable the Gmail API, and obtain the necessary API credentials.

Step 1: Create a GCP Project

Go to the Google Cloud Console: https://console.cloud.google.com/
Sign in with your Google account.
Click on the project dropdown and select “New Project.”
Enter a project name, and click “Create.”
Step 2: Enable the Gmail API

In your new GCP project, click on “APIs & Services” > “Library.”
Search for “Gmail API” and click on it.
Click “Enable.”
Step 3: Obtain API Credentials

Click on “APIs & Services” > “Credentials.”
Click “Create credentials” and select “OAuth client ID.”
Select “Desktop App” as the application type, enter a name, and click “Create.”
Download the JSON file containing your client ID and client secret.
Step 4: Authorize Your Python Script

To access your Gmail account, you will need to authorize your Python script. Create a new Python file and add the following code:

import os
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

def main():
# Load your client secrets from the downloaded JSON file
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
CLIENT_SECRETS_FILE = "path/to/your/client_secrets.json"

# The scopes your app will request access to
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
# Start the OAuth flow
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
CLIENT_SECRETS_FILE, SCOPES)

# Prompt the user to authorize the app
credentials = flow.run_local_server(port=0)

# Build the Gmail API client
service = build('gmail', 'v1', credentials=credentials)

# Your Gmail API logic goes here
# ...

if name == 'main':
main()

Reading and Filtering Emails

Now that you have connected to your Gmail account, you can use the Gmail API to read and filter your emails. To retrieve a list of emails, you can use the `messages().list()` method:

def get_emails(service, query=''):
results = service.users().messages().list(userId='me', q=query).execute()
messages = results.get('messages', [])
return messages

You can filter your emails by passing a query string to the get_emails() function. For example, to retrieve all unread emails, you can call the function like this:

unread_emails = get_emails(service, query='is:unread')

Sorting and Organizing Emails

With the list of emails retrieved, you can use Python to sort and organize them. For instance, you can sort emails by date, sender, or subject.

To sort emails by date, you can use the get_email_date() function:

import dateparser

def get_email_date(service, email_id):
email = service.users().messages().get(userId='me', id=email_id).execute()
headers = email['payload']['headers']

for header in headers:
if header['name'] == 'Date':
return dateparser.parse(header['value'])

return None

Then, you can use the sorted() function to sort the list of emails:

sorted_emails = sorted(unread_emails, key=lambda email: get_email_date(service, email['id']), reverse=True)

Automating Email Responses

If you receive many similar emails and want to automate your responses, you can use Python to send automatic replies based on specific conditions.

First, create a function to send an email:

from googleapiclient.errors import HttpError
from email.mime.text import MIMEText
import base64

def send_email(service, to, subject, body):
try:
message = MIMEText(body)
message['to'] = to
message['subject'] = subject
create_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
send_message = (service.users().messages().send(userId="me", body=create_message).execute())
print(F'sent message to {to} Message Id: {send_message["id"]}')
except HttpError as error:
print(F'An error occurred: {error}')
send_message = None
return send_message

Next, define a function that analyzes incoming emails and sends an automatic response if specific conditions are met:

def process_emails(service, emails):
for email in emails:
email_id = email['id']
email_data = service.users().messages().get(userId='me', id=email_id).execute()

# Extract the sender's email address and the subject
headers = email_data['payload']['headers']
sender = ''
subject = ''

for header in headers:
if header['name'] == 'From':
sender = header['value']
if header['name'] == 'Subject':
subject = header['value']

# Define your conditions and response templates
if 'specific_keyword' in subject.lower():
response_subject = 'Automated response to your email'
response_body = f"Dear {sender},\n\nThank you for your email regarding 'specific_keyword'.\n\nBest regards,\nYour Name"

# Send the automatic response
send_email(service, sender, response_subject, response_body)

# Mark the email as read
service.users().messages().modify(userId='me', id=email_id, body={'removeLabelIds': ['UNREAD']}).execute()

Replace ‘specific_keyword’ with a keyword you want to look for in the subject of incoming emails. If the keyword is found, the script will send an automatic response and mark the email as read. You can customize the response subject and body as needed.

Scheduling Email Reminders

You can also use Python to schedule email reminders for important events or tasks. To do this, you can use the schedule library. First, install the library using pip:

pip install schedule

Next, create a function that sends a reminder email:

def send_reminder_email(service, to, event, datetime):
subject = f'Reminder: {event}'
body = f'Dear {to},\n\nThis is a reminder for the following event:\n\n{event}\nDate and time: {datetime}\n\nBest regards,\nYour Name'
send_email(service, to, subject, body)

Now, you can use the schedule library to schedule the reminder email:

import schedule
import time

# Define your reminder
to = 'recipient@example.com'
event = 'Important Meeting'
datetime = '2023-05-01 10:00:00'

# Schedule the reminder email
schedule.every().day.at('08:00').do(send_reminder_email, service, to, event, datetime)

# Keep the script running and checking for scheduled tasks
while True:
schedule.run_pending()
time.sleep(60)

This script will send a reminder email every day at 8:00 AM until the event takes place. You can adjust the recipient, event name, and date/time as needed.

Conclusion

In this article, we have explored various ways to use Python and the Gmail API to manage and organize your Gmail inbox more efficiently. By leveraging the power of Python, you can automate repetitive tasks, such as sending email responses and scheduling reminders, ultimately saving you time and effort.

Remember to experiment with different email filters, sorting methods, and automation techniques to find the combination that works best for your specific needs. With a little creativity, you can make Python an indispensable tool for mastering your Gmail inbox.

--

--