Files
platform/seed/skills/google-mail-api/README.md
T
2026-02-24 21:47:36 +00:00

209 lines
5.6 KiB
Markdown

# 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:**
```python
service = authenticate() # Returns service object
```
**Node.js/TypeScript:**
```typescript
const auth = await authenticate(); // Returns OAuth2Client
const gmail = google.gmail({ version: "v1", auth });
```
### Making API Calls
**Python:**
```python
results = service.users().messages().list(userId="me").execute()
```
**Node.js/TypeScript:**
```typescript
const results = await gmail.users.messages.list({ userId: "me" });
```
### Handling Responses
**Python:**
```python
messages = results.get("messages", [])
```
**Node.js/TypeScript:**
```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
1. ✅ List Labels
2. ✅ List Messages in Inbox
3. ✅ Get Full Message
4. ✅ Send a Message
5. ✅ Send Email with Attachment
6. ✅ Create Draft
7. ✅ Apply Label to Message
8. ✅ List Threads
9. ✅ Get Thread Messages in Order
10. ✅ Search Messages
11. ✅ Create Custom Label
12. ✅ Modify Thread Labels
13. ✅ Move Message to Trash
14. ✅ Delete Message Permanently
15. ✅ Batch Modify Messages
16. ✅ Get User Profile
## Authentication Setup (Both Languages)
### 1. Create Google Cloud Project
- Go to [Google Cloud Console](https://console.cloud.google.com/)
- 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:
```typescript
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:
```python
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()` and `batchDelete()` for multiple messages
- **Pagination**: Use `pageToken` for large result sets
- **Caching**: Cache label IDs and user profiles
## Error Handling
### Python
```python
from googleapiclient.errors import HttpError
try:
result = service.users().messages().get(...).execute()
except HttpError as error:
print(f"Error: {error}")
```
### Node.js/TypeScript
```typescript
try {
const result = await gmail.users.messages.get(...);
} catch (error: any) {
console.error(`Error ${error.response.status}: ${error.message}`);
}
```
## Resources
- [Official Gmail API Docs](https://developers.google.com/workspace/gmail/api/guides)
- [API Reference](https://developers.google.com/workspace/gmail/api/reference/rest)
- [Python Client](https://googleapis.github.io/google-api-python-client/)
- [Node.js Client](https://github.com/googleapis/google-api-nodejs-client)
- [OAuth 2.0 Setup](https://developers.google.com/identity/protocols/oauth2)
## Tips & Tricks
1. **Caching Labels**: Call `list()` once and cache label IDs to avoid repeated API calls
2. **Batch Operations**: Group message operations into batch calls
3. **Full vs Metadata Format**: Use `format="metadata"` when you only need headers
4. **Thread vs Messages**: Use threads for conversation view, messages for individual emails
5. **Custom Queries**: Learn Gmail search syntax for powerful `q` parameter usage
## Examples
### Python: Send Email Script
```bash
python examples/send_email.py --to recipient@example.com --subject "Hello"
```
### Node.js: Create TypeScript Utility
```bash
npx ts-node src/gmail-utility.ts
```
Both implementations provide all the tools needed to build production Gmail automation!