Automate Email Reports with Python and Gmail API

Automate Email Reports with Python and Gmail API

Automate Email Reports with Python and Gmail API

 

Automating routine tasks like sending daily or weekly email reports can help reduce manual work and improve efficiency for developers and teams. In this post, we will explore how to use Python alongside Google’s Gmail API to send automated reports, using data sourced from files or APIs. We’ll walk through everything from setting up the Gmail API to coding a complete solution that fetches data, formats it, and sends it out via email.

1. Setting Up Gmail API with Python

Before sending emails via Gmail API, we need to enable it in Google Cloud Console and configure OAuth2 credentials for our application.

Step-by-step Setup:

  • Go to Google Cloud Console
  • Create or select a project
  • Enable the Gmail API
  • Create OAuth 2.0 credentials
  • Download the credentials.json file

Next, install the required libraries:

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

Then authorize access and store the token:

from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
import os.path
import pickle

SCOPES = ['https://www.googleapis.com/auth/gmail.send']

creds = None
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
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)
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('gmail', 'v1', credentials=creds)

2. Formatting Email Messages in Python

Now that we’re authenticated, we can create and send an email. We’ll use the built-in email library to structure our MIME message.

from email.mime.text import MIMEText
import base64

def create_message(sender, to, subject, message_text):
    message = MIMEText(message_text, 'plain')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
    return {'raw': raw_message}

Use this to create an email and send it:

def send_email(service, user_id, message):
    return service.users().messages().send(userId=user_id, body=message).execute()

3. Aggregating Data for Reports

Our goal is to generate reports dynamically. Let’s say we fetch JSON data from a public API or parse a local CSV file. Here’s an example using a dummy dataset and formatting it into a readable report:

import requests

def fetch_dummy_data():
    response = requests.get('https://jsonplaceholder.typicode.com/posts?_limit=5')
    response.raise_for_status()
    return response.json()

def format_report(data):
    report_lines = ["Daily Report:\n"]
    for item in data:
        report_lines.append(f"Title: {item['title']}\nBody: {item['body']}\n---")
    return "\n".join(report_lines)

This generates a text-based report that you can inject into your email message body.

4. Automating and Scheduling the Email Task

You can automate this process via cron (Linux/macOS) or Task Scheduler (Windows). Here’s a complete Python script to tie everything together:

def main():
    # Authenticate
    service = build('gmail', 'v1', credentials=creds)
    
    # Fetch and format report
    data = fetch_dummy_data()
    report = format_report(data)
    
    # Create and send email
    message = create_message(
        sender="your_email@gmail.com",
        to="recipient@example.com",
        subject="Daily Automated Report",
        message_text=report
    )
    result = send_email(service, "me", message)
    print("Email sent! Message ID:", result['id'])

if __name__ == '__main__':
    main()

Schedule this script using cron:

0 9 * * * /usr/bin/python3 /path/to/your_script.py

5. Best Practices and Optimization Tips

Here are some important considerations when deploying automated email reports at scale:

  • Rate limiting: Gmail API has usage quotas. Avoid sending too many emails rapidly.
  • Error handling: Use try-except blocks around API calls to gracefully handle failures.
  • Credential security: Do not commit credentials or token files to version control.
  • HTML emails: Use MIMEText(..., 'html') for rich text formatting where needed.
  • Email batching: Consider aggregating multiple reports in a single email to stay within quota limits.

With Gmail API and Python, report automation is not only efficient but also completely customizable for different data pipelines. Whether you’re a data analyst, developer, or infrastructure engineer, this solution can save time and streamline your workflow.

 

Useful links: