Step-by-Step Guide: Build a Gmail API–Based RPA Tool Using Python

In this article, we will build a Python-based RPA tool that can log in to Gmail securely using Google OAuth, download attachments from emails, and save them automatically to a local drive — without browser automation.

This approach is safe, Google-compliant, and production-ready.

Step 1: Prerequisites

Before starting, ensure you have the following:

  • Python 3.9+ installed

  • Basic knowledge of Python

  • Gmail account

  • Internet connection

  • Optional: VS Code or any Python IDE

Step 2: Set Up Project Folder and Virtual Environment

  1. Create a project folder:

mkdir Gmail-RPA
cd Gmail-RPA

Create a virtual environment:

python -m venv venv

Activate the virtual environment:

# Windows
venv\Scripts\activate
  1. Upgrade pip:

python -m pip install --upgrade pip

Step 3: Install Required Packages

Install the required Python packages:

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

These libraries help us interact with the Gmail API and handle OAuth authentication.

Step 4: Set Up Google Cloud Project

  1. Go to Google Cloud Console.

  2. Click Select Project → New Project.

  3. Name your project: Gmail-RPA.

  4. Click Create.

Step 5: Enable Gmail API

  1. In the Google Cloud Console, go to:

APIs & Services → Library
  1. Search for Gmail API.

  2. Click Enable.

Step 6: Configure OAuth Consent Screen

  1. Go to:

APIs & Services → OAuth consent screen
  1. Select User Type → External.

  2. App name: Gmail RPA Tool.

  3. User support email: your Gmail.

  4. Add your Gmail as a Test User.

  5. Save.

Adding yourself as a test user ensures Google allows your app to access your Gmail even though the app is unverified.

Step 7: Create OAuth Client ID

  1. Go to:

APIs & Services → Credentials → Create Credentials → OAuth Client ID
  1. Application type: Desktop App.

  2. Name: Gmail RPA Desktop.

  3. Click Create.

  4. Click Download JSON.

  5. Rename the downloaded file to:

credentials.json
  1. Place it in your project folder:

Gmail-RPA/

Step 8: Create Python Script to Download Attachments

Create run.py and paste the following code:

import os
import base64
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

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

def gmail_auth():
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    else:
        flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return build('gmail', 'v1', credentials=creds)

def download_attachments():
    service = gmail_auth()
    results = service.users().messages().list(userId='me', q='has:attachment').execute()
    messages = results.get('messages', [])

    save_path = "D:/gmail_files"
    os.makedirs(save_path, exist_ok=True)

    for msg in messages[:5]:  # download first 5 emails with attachments
        message = service.users().messages().get(userId='me', id=msg['id']).execute()
        for part in message['payload'].get('parts', []):
            if part.get('filename'):
                att_id = part['body']['attachmentId']
                att = service.users().messages().attachments().get(
                    userId='me', messageId=msg['id'], id=att_id).execute()

                data = base64.urlsafe_b64decode(att['data'])
                file_path = os.path.join(save_path, part['filename'])

                with open(file_path, 'wb') as f:
                    f.write(data)

                print("Downloaded:", file_path)

if __name__ == "__main__":
    download_attachments()

Step 9: Run the Script

  1. Make sure your virtual environment is active:

venv\Scripts\activate
  1. Run the script:

python run.py
  1. First-time login:

  • Browser opens

  • Click Advanced → Go to Gmail RPA Tool (unsafe)

  • Login with Gmail and click Allow

  1. After successful login, a token.json file is created.

  2. Attachments will be downloaded to D:/gmail_files.

Step 10: Automate & Extend

  • Filter emails by sender or subject

  • Download only PDF/Excel files

  • Rename files automatically

  • Move files to organized folders: E:/Reports/YYYY/MM/

  • Schedule daily execution using Windows Task Scheduler

Conclusion

Using the Gmail API with Python, you can create a secure, automated workflow to download email attachments. This method is faster, safer, and Google-compliant compared to browser automation.