| name | google-gmail-integration |
| description | Manages Gmail through the Gmail API. Search and read emails, send messages, manage labels and filters, handle attachments, and automate email workflows. Use when working with Gmail, reading/sending emails, searching inbox, managing email organization, or processing email data. |
Gmail Integration
Comprehensive Gmail integration enabling email search, message management, sending, label organization, attachment handling, and workflow automation through the Gmail API v1.
Quick Start
When asked to work with Gmail:
- Authenticate: Set up OAuth2 credentials (one-time setup)
- Search emails: Find messages by sender, subject, date, or content
- Read messages: Get email content and attachments
- Send emails: Compose and send messages
- Organize: Create labels, apply filters, archive messages
- Automate: Process emails based on rules
Prerequisites
One-Time Setup
1. Enable Gmail API:
2. Create OAuth2 Credentials:
3. Install Dependencies:
pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client --break-system-packages
4. Initial Authentication:
python scripts/authenticate.py
See reference/setup-guide.md for detailed setup instructions.
Core Operations
Search Emails
Basic search:
python scripts/search_emails.py --query "project update"
python scripts/search_emails.py --from "boss@company.com"
python scripts/search_emails.py --subject "Weekly Report"
python scripts/search_emails.py --unread
python scripts/search_emails.py --label "Important"
Advanced search queries:
query = "from:boss@company.com subject:urgent is:unread"
query = "after:2025/01/01 before:2025/01/31"
query = "has:attachment filename:pdf"
query = "larger:10M"
query = "category:primary"
query = "category:social"
query = "category:promotions"
query = "(from:alice@company.com OR from:bob@company.com) subject:meeting"
See reference/search-syntax.md for complete search reference.
Read Messages
Get message content:
python scripts/read_email.py --message-id MESSAGE_ID
python scripts/read_email.py --message-id MESSAGE_ID --format full
python scripts/read_email.py --message-id MESSAGE_ID --format minimal
python scripts/read_email.py --message-id MESSAGE_ID --format raw
Extract information:
python scripts/get_headers.py --message-id MESSAGE_ID
python scripts/get_body.py --message-id MESSAGE_ID --format text
python scripts/get_body.py --message-id MESSAGE_ID --format html
python scripts/list_attachments.py --message-id MESSAGE_ID
Download attachments:
python scripts/download_attachments.py --message-id MESSAGE_ID --output ./downloads/
python scripts/download_attachments.py --message-id MESSAGE_ID --filename "report.pdf"
Send Emails
Simple send:
python scripts/send_email.py \
--to "recipient@example.com" \
--subject "Hello" \
--body "Email content here"
python scripts/send_email.py \
--to "user1@example.com,user2@example.com" \
--cc "manager@example.com" \
--subject "Team Update" \
--body "Content here"
Send with attachments:
python scripts/send_email.py \
--to "recipient@example.com" \
--subject "Report" \
--body "Please see attached" \
--attachments "./report.pdf,./data.xlsx"
Send HTML email:
python scripts/send_email.py \
--to "recipient@example.com" \
--subject "Newsletter" \
--html-body "./newsletter.html"
Reply to message:
python scripts/reply_email.py \
--message-id MESSAGE_ID \
--body "Thanks for your email..."
Forward message:
python scripts/forward_email.py \
--message-id MESSAGE_ID \
--to "colleague@example.com" \
--body "FYI"
Label Management
Create labels:
python scripts/create_label.py --name "Project Alpha"
python scripts/create_label.py --name "Projects/Alpha"
python scripts/create_label.py \
--name "Important" \
--label-list-visibility show \
--message-list-visibility show
Apply labels:
python scripts/add_label.py --message-id MESSAGE_ID --label "Important"
python scripts/add_label.py --message-id MESSAGE_ID --labels "Work,Urgent"
python scripts/remove_label.py --message-id MESSAGE_ID --label "Inbox"
List labels:
python scripts/list_labels.py
python scripts/get_label_id.py --name "Project Alpha"
Message Management
Mark as read/unread:
python scripts/mark_read.py --message-id MESSAGE_ID
python scripts/mark_unread.py --message-id MESSAGE_ID
Archive/Trash:
python scripts/archive_email.py --message-id MESSAGE_ID
python scripts/trash_email.py --message-id MESSAGE_ID
python scripts/delete_email.py --message-id MESSAGE_ID
Batch operations:
python scripts/batch_archive.py --days 30 --read-only
python scripts/batch_delete.py --from "spam@example.com"
python scripts/batch_mark_read.py --label "Inbox"
Common Workflows
Workflow 1: Process Unread Emails
Scenario: Read unread emails and categorize
python scripts/process_unread.py \
--label-rules rules.json \
--mark-read
{
"rules": [
{
"condition": "from:boss@company.com",
"action": "add_label",
"label": "Important"
},
{
"condition": "subject:invoice",
"action": "add_label",
"label": "Finance"
}
]
}
Workflow 2: Email to Task Conversion
Scenario: Convert emails into task format
python scripts/email_to_tasks.py \
--query "label:To-Do" \
--output tasks.json \
--mark-done
Workflow 3: Automated Responses
Scenario: Send auto-replies based on conditions
python scripts/auto_respond.py \
--query "from:client@company.com subject:urgent" \
--template response_template.txt \
--label "Auto-Responded"
Workflow 4: Email Backup
Scenario: Download emails for backup
python scripts/backup_emails.py \
--output ./email_backup/ \
--format mbox
python scripts/backup_emails.py \
--label "Important" \
--output ./important_backup/ \
--include-attachments
Workflow 5: Email Analytics
Scenario: Analyze email patterns
python scripts/email_stats.py \
--start-date 2025-01-01 \
--end-date 2025-01-31 \
--output stats.json
python scripts/top_senders.py --limit 10
python scripts/email_volume.py --days 30
Search Query Syntax
Operators
"from:sender@example.com"
"to:recipient@example.com"
"cc:person@example.com"
"bcc:person@example.com"
"subject:meeting"
"subject:(status report)"
"after:2025/01/01"
"before:2025/12/31"
"older_than:2d"
"newer_than:7d"
"is:unread"
"is:read"
"is:starred"
"is:important"
"has:attachment"
"has:drive"
"has:document"
"has:spreadsheet"
"has:presentation"
"has:youtube"
"larger:10M"
"smaller:1M"
"size:5M"
"category:primary"
"category:social"
"category:promotions"
"category:updates"
"category:forums"
"label:important"
"label:work"
"-label:inbox"
"filename:pdf"
"filename:report.xlsx"
"in:inbox"
"in:trash"
"in:spam"
"in:anywhere"
"OR"
"AND"
"-"
"()"
Example Queries
"from:boss@company.com is:unread"
"has:attachment larger:5M"
"is:important is:unread newer_than:7d"
"from:client@company.com subject:invoice has:attachment filename:pdf"
"(from:alice@company.com OR from:bob@company.com) subject:meeting"
"after:2025/01/01 before:2025/01/31 project update"
"-category:promotions -category:social is:unread"
Message Format Options
Format Types
format = 'minimal'
format = 'full'
format = 'raw'
format = 'metadata'
Accessing Message Parts
headers = message['payload']['headers']
for header in headers:
if header['name'] == 'Subject':
subject = header['value']
elif header['name'] == 'From':
sender = header['value']
parts = message['payload'].get('parts', [])
for part in parts:
if part['mimeType'] == 'text/plain':
body = base64.urlsafe_b64decode(part['body']['data']).decode()
for part in parts:
if part.get('filename'):
attachment_id = part['body']['attachmentId']
Sending Email Formats
Plain Text
from email.mime.text import MIMEText
import base64
message = MIMEText('Email body')
message['to'] = 'recipient@example.com'
message['subject'] = 'Test Email'
raw = base64.urlsafe_b64encode(message.as_bytes()).decode()
HTML Email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
message = MIMEMultipart('alternative')
message['to'] = 'recipient@example.com'
message['subject'] = 'HTML Email'
text = "Plain text version"
html = "<html><body><h1>HTML Version</h1></body></html>"
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
message.attach(part1)
message.attach(part2)
With Attachments
from email.mime.base import MIMEBase
from email import encoders
import os
message = MIMEMultipart()
message['to'] = 'recipient@example.com'
message['subject'] = 'With Attachment'
body = MIMEText('Please see attached')
message.attach(body)
with open('file.pdf', 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header(
'Content-Disposition',
f'attachment; filename={os.path.basename("file.pdf")}'
)
message.attach(part)
Label Visibility
Label list visibility:
labelShow - Show in label list
labelHide - Hide from label list
Message list visibility:
show - Show label in message list
hide - Hide label in message list
API Rate Limits
Gmail API quotas:
- Queries per day: 1,000,000,000
- Queries per 100 seconds per user: 250
- Send message: 100 per day per user (can request increase)
Best practices:
- Batch requests when possible
- Use partial responses to reduce data
- Implement exponential backoff
- Cache message IDs and metadata
OAuth Scopes
'https://www.googleapis.com/auth/gmail.modify'
'https://www.googleapis.com/auth/gmail.readonly'
'https://www.googleapis.com/auth/gmail.send'
'https://www.googleapis.com/auth/gmail.labels'
'https://www.googleapis.com/auth/gmail.compose'
'https://www.googleapis.com/auth/gmail.insert'
'https://www.googleapis.com/auth/gmail.metadata'
Choose the minimal scope needed for your use case.
Scripts Reference
Authentication:
authenticate.py - Initial OAuth setup
refresh_token.py - Refresh token
Search:
search_emails.py - Search with queries
find_by_sender.py - Quick sender search
find_unread.py - Get unread messages
Read:
read_email.py - Read message content
get_headers.py - Extract headers
get_body.py - Get message body
list_attachments.py - List attachments
download_attachments.py - Download files
Send:
send_email.py - Send new email
reply_email.py - Reply to message
forward_email.py - Forward message
send_bulk.py - Send to multiple recipients
Labels:
create_label.py - Create new label
list_labels.py - Get all labels
add_label.py - Apply label to message
remove_label.py - Remove label
Manage:
mark_read.py - Mark as read
mark_unread.py - Mark as unread
archive_email.py - Archive message
trash_email.py - Move to trash
delete_email.py - Permanent delete
Batch:
batch_archive.py - Archive multiple
batch_delete.py - Delete multiple
batch_mark_read.py - Mark multiple read
Automation:
process_unread.py - Process unread emails
auto_respond.py - Automated responses
email_to_tasks.py - Extract tasks
apply_filters.py - Apply rule-based filters
Analytics:
email_stats.py - Usage statistics
top_senders.py - Most frequent senders
email_volume.py - Volume over time
Best Practices
- Use specific queries: Narrow searches reduce processing time
- Batch operations: Process multiple messages in single API call
- Cache data: Store message IDs and metadata locally
- Handle pagination: Use pageToken for large result sets
- Respect quotas: Monitor API usage
- Error handling: Implement retry logic with backoff
- Secure tokens: Never commit token.json to version control
- Minimal scopes: Request only needed permissions
Integration Examples
See examples/ for complete workflows:
Troubleshooting
"Token expired"
rm token.json
python scripts/authenticate.py
"Insufficient permissions"
- Check SCOPES in authenticate.py
- Delete token.json and re-auth with new scopes
"Message not found"
- Message may have been deleted
- Check if in trash or spam
"Rate limit exceeded"
- Implement delays between requests
- Use batch operations
- Request quota increase if needed
Reference Documentation