5.6 KiB
5.6 KiB
Google Mail API Skill
Complete documentation for the Gmail API with support for both Python and Node.js/TypeScript.
Files
- SKILL.md - Python implementation with
google-api-python-client - SKILL-nodejs.md - Node.js/TypeScript implementation with
googleapis - README.md - This file
Quick Comparison
| Feature | Python | Node.js/TypeScript |
|---|---|---|
| Installation | pip install google-api-python-client |
npm install googleapis google-auth-library |
| Authentication | OAuth 2.0 with token caching | OAuth 2.0 with token caching |
| Type Safety | Dynamic typing | Full TypeScript support |
| Performance | Slower | Faster, async/await native |
| Use Cases | Scripts, automation, legacy | Modern web, backends, real-time |
| Dependencies | google-api-python-client, google-auth-oauthlib | googleapis, google-auth-library |
| Maintenance | ✅ Maintained | ✅ Actively maintained |
Which Should I Use?
Choose Python if:
- You're already in a Python environment (Jupyter, scripts)
- You're doing data analysis with pandas
- You prefer simpler blocking APIs
- You need to integrate with existing Python tools
Choose Node.js/TypeScript if:
- You're building a web service or API
- You want async/await and promises
- You need type safety (TypeScript)
- You're already using Node.js
- You need better performance
- You want to build real-time features
Core Differences
Authentication
Python:
service = authenticate() # Returns service object
Node.js/TypeScript:
const auth = await authenticate(); // Returns OAuth2Client
const gmail = google.gmail({ version: "v1", auth });
Making API Calls
Python:
results = service.users().messages().list(userId="me").execute()
Node.js/TypeScript:
const results = await gmail.users.messages.list({ userId: "me" });
Handling Responses
Python:
messages = results.get("messages", [])
Node.js/TypeScript:
const messages = results.data.messages || [];
Common Tasks
All recipes are available in both:
SKILL.md(Python versions)SKILL-nodejs.md(Node.js/TypeScript versions)
Available Recipes
- ✅ List Labels
- ✅ List Messages in Inbox
- ✅ Get Full Message
- ✅ Send a Message
- ✅ Send Email with Attachment
- ✅ Create Draft
- ✅ Apply Label to Message
- ✅ List Threads
- ✅ Get Thread Messages in Order
- ✅ Search Messages
- ✅ Create Custom Label
- ✅ Modify Thread Labels
- ✅ Move Message to Trash
- ✅ Delete Message Permanently
- ✅ Batch Modify Messages
- ✅ Get User Profile
Authentication Setup (Both Languages)
1. Create Google Cloud Project
- Go to Google Cloud Console
- Create new project
- Enable Gmail API
- Create OAuth 2.0 credentials (Desktop Application)
- Download credentials file as
credentials.json
2. Set Scopes
https://www.googleapis.com/auth/gmail.modify
https://www.googleapis.com/auth/gmail.send
https://www.googleapis.com/auth/gmail.readonly
3. First Run
Both implementations will prompt you to authorize via your browser and save a token for future use.
Helper Classes/Utilities
Node.js: GmailHelper Class
Already provided in SKILL-nodejs.md. Wraps common operations:
const helper = new GmailHelper(auth);
await helper.sendMessage(to, subject, body);
await helper.applyLabel(messageId, labelName);
await helper.listInboxMessages(10);
Python: Create Your Own
Consider wrapping the service in a class for easier reuse:
class GmailHelper:
def __init__(self, service):
self.service = service
def send_message(self, to, subject, body):
# ... implementation
Rate Limiting & Best Practices
Both implementations should respect:
- Quota: 250 requests per second per user
- Batch operations: Use
batchModify()andbatchDelete()for multiple messages - Pagination: Use
pageTokenfor large result sets - Caching: Cache label IDs and user profiles
Error Handling
Python
from googleapiclient.errors import HttpError
try:
result = service.users().messages().get(...).execute()
except HttpError as error:
print(f"Error: {error}")
Node.js/TypeScript
try {
const result = await gmail.users.messages.get(...);
} catch (error: any) {
console.error(`Error ${error.response.status}: ${error.message}`);
}
Resources
Tips & Tricks
- Caching Labels: Call
list()once and cache label IDs to avoid repeated API calls - Batch Operations: Group message operations into batch calls
- Full vs Metadata Format: Use
format="metadata"when you only need headers - Thread vs Messages: Use threads for conversation view, messages for individual emails
- Custom Queries: Learn Gmail search syntax for powerful
qparameter usage
Examples
Python: Send Email Script
python examples/send_email.py --to recipient@example.com --subject "Hello"
Node.js: Create TypeScript Utility
npx ts-node src/gmail-utility.ts
Both implementations provide all the tools needed to build production Gmail automation!