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:
Step 2: Set Up Project Folder and Virtual Environment
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
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
Go to Google Cloud Console.
Click Select Project → New Project.
Name your project: Gmail-RPA.
Click Create.
Step 5: Enable Gmail API
In the Google Cloud Console, go to:
APIs & Services → Library
Search for Gmail API.
Click Enable.
Step 6: Configure OAuth Consent Screen
Go to:
APIs & Services → OAuth consent screen
Select User Type → External.
App name: Gmail RPA Tool.
User support email: your Gmail.
Add your Gmail as a Test User.
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
Go to:
APIs & Services → Credentials → Create Credentials → OAuth Client ID
Application type: Desktop App.
Name: Gmail RPA Desktop.
Click Create.
Click Download JSON.
Rename the downloaded file to:
credentials.json
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
Make sure your virtual environment is active:
venv\Scripts\activate
Run the script:
python run.py
First-time login:
After successful login, a token.json file is created.
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.