Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 09:05:19 +08:00
commit 09fec2555b
96 changed files with 24269 additions and 0 deletions

View File

@@ -0,0 +1,659 @@
# gmaillm API Reference
Complete reference for gmaillm Python library and CLI.
## Table of Contents
- [Python Library API](#python-library-api)
- [CLI Commands](#cli-commands)
- [Models & Types](#models--types)
- [Gmail Search Syntax](#gmail-search-syntax)
---
## Python Library API
### GmailClient
```python
from gmaillm import GmailClient
client = GmailClient(
credentials_file="/Users/wz/.gmail-mcp/credentials.json", # optional
oauth_keys_file="/Users/wz/Desktop/OAuth2/gcp-oauth.keys.json" # optional
)
```
### Core Operations
#### verify_setup()
Verify authentication and basic functionality.
```python
result = client.verify_setup()
# Returns: {
# 'auth': bool,
# 'folders': int,
# 'inbox_accessible': bool,
# 'errors': List[str]
# }
```
#### list_emails()
List emails with pagination.
```python
result = client.list_emails(
folder='INBOX', # Gmail label/folder
max_results=10, # 1-50, default 10
page_token=None, # For pagination
query=None # Gmail search query
)
# Returns: SearchResult
```
**Example:**
```python
# First page
result = client.list_emails(folder='INBOX', max_results=10)
for email in result.emails:
print(email.to_markdown())
# Next page
if result.next_page_token:
next_result = client.list_emails(
folder='INBOX',
max_results=10,
page_token=result.next_page_token
)
```
#### read_email()
Read a specific email.
```python
email = client.read_email(
message_id, # Required: message ID
format="summary" # "summary" | "full"
)
# Returns: EmailSummary | EmailFull
```
**Formats:**
- `"summary"` (default): ID, from, to, subject, date, snippet, labels
- `"full"`: Everything + body (plain text & HTML), attachments
**Example:**
```python
# Get summary first (minimal context)
summary = client.read_email(msg_id, format="summary")
print(summary.to_markdown())
# Get full if body needed
full = client.read_email(msg_id, format="full")
print(full.body_plain)
```
#### search_emails()
Search emails using Gmail query syntax.
```python
result = client.search_emails(
query, # Gmail search query
folder='INBOX', # Optional: limit to folder
max_results=10 # 1-50, default 10
)
# Returns: SearchResult
```
**Example:**
```python
result = client.search_emails(
query="from:professor@university.edu has:attachment after:2024/10/01",
max_results=20
)
```
#### get_thread()
Get all emails in a conversation thread.
```python
messages = client.get_thread(message_id)
# Returns: List[EmailSummary] (chronologically sorted)
```
**Example:**
```python
thread = client.get_thread(msg_id)
print(f"Thread has {len(thread)} messages")
for i, msg in enumerate(thread, 1):
print(f"[{i}] {msg.from_.email}{msg.to[0].email if msg.to else 'unknown'}")
print(f" {msg.subject}")
```
#### send_email()
Send a new email.
```python
from gmaillm import SendEmailRequest
request = SendEmailRequest(
to=["user@example.com"], # Required: list of recipients
subject="Subject", # Required: string
body="Email body", # Required: string
cc=["cc@example.com"], # Optional: list
attachments=["/path/to/file.pdf"] # Optional: list of file paths
)
response = client.send_email(request)
# Returns: SendEmailResponse
```
**Example:**
```python
request = SendEmailRequest(
to=["friend@gmail.com"],
subject="Quick Question",
body="Hey, are you free tomorrow?\n\nBest,\nWarren"
)
response = client.send_email(request)
if response.success:
print(f"Sent! Message ID: {response.message_id}")
```
#### reply_email()
Reply to an existing email.
```python
response = client.reply_email(
message_id, # Required: original message ID
body, # Required: reply body text
reply_all=False # Optional: reply to all recipients
)
# Returns: SendEmailResponse
```
**Example:**
```python
response = client.reply_email(
message_id="19abc123",
body="Thanks for the update!",
reply_all=False
)
```
#### get_folders()
List all Gmail labels/folders.
```python
folders = client.get_folders()
# Returns: List[Folder]
```
**Example:**
```python
folders = client.get_folders()
for folder in folders:
print(f"{folder.name}: {folder.unread_count} unread")
```
#### modify_labels()
Add or remove labels from an email.
```python
client.modify_labels(
message_id, # Required: message ID
add_labels=['STARRED'], # Optional: labels to add
remove_labels=['UNREAD'] # Optional: labels to remove
)
```
**Common operations:**
```python
# Mark as read
client.modify_labels(msg_id, remove_labels=['UNREAD'])
# Star email
client.modify_labels(msg_id, add_labels=['STARRED'])
# Archive (remove from inbox)
client.modify_labels(msg_id, remove_labels=['INBOX'])
# Move to trash
client.modify_labels(msg_id, add_labels=['TRASH'])
```
#### delete_email()
Delete a single email.
```python
success = client.delete_email(
message_id, # Required: message ID
permanent=False # Optional: True = permanent, False = trash
)
# Returns: bool
```
---
## CLI Commands
All commands use the `mail` entry point. For now, use:
```bash
python3 -m gmaillm.cli <command>
```
Or create an alias:
```bash
alias gmail='python3 -m gmaillm.cli'
```
### gmail verify
Check authentication and setup.
```bash
gmail verify
```
### gmail list
List emails from a folder.
```bash
gmail list # Default: INBOX, 10 results
gmail list --folder SENT # List from SENT folder
gmail list --max 20 # Get 20 results
gmail list --query "is:unread" # With search query
```
**Options:**
- `--folder FOLDER` - Folder/label to list from (default: INBOX)
- `--max N` - Maximum results (1-50, default: 10)
- `--query QUERY` - Gmail search query
### gmail read
Read a specific email.
```bash
gmail read <message_id> # Summary (default)
gmail read <message_id> --full # Full body
```
**Options:**
- `--full` - Show full email body (instead of summary)
### gmail thread
Show entire email conversation.
```bash
gmail thread <message_id>
```
### gmail search
Search emails.
```bash
gmail search "from:example@gmail.com"
gmail search "has:attachment" --max 20
gmail search "is:unread after:2024/10/01" --folder INBOX
```
**Options:**
- `--folder FOLDER` - Limit search to folder (default: INBOX)
- `--max N` - Maximum results (1-50, default: 10)
### gmail reply
Reply to an email.
```bash
gmail reply <message_id> --body "Thanks!"
gmail reply <message_id> --body "Sounds good" --reply-all
```
**Options:**
- `--body TEXT` - Required: reply body text
- `--reply-all` - Reply to all recipients (default: reply to sender only)
**Confirmation:** Always shows preview and asks "Send? (y/n/yolo)"
### gmail send
Send a new email.
```bash
gmail send \
--to user@example.com \
--subject "Subject" \
--body "Body text"
# With multiple recipients
gmail send \
--to user1@example.com user2@example.com \
--cc boss@example.com \
--subject "Report" \
--body "See attached" \
--attachments report.pdf data.xlsx
# Skip confirmation with YOLO mode
gmail send --to user@example.com --subject "Test" --body "Hi" --yolo
```
**Options:**
- `--to EMAIL [EMAIL...]` - Required: recipient email(s)
- `--subject TEXT` - Required: email subject
- `--body TEXT` - Required: email body
- `--cc EMAIL [EMAIL...]` - Optional: CC recipient(s)
- `--attachments FILE [FILE...]` - Optional: file path(s) to attach
- `--yolo` - Skip confirmation, send immediately
### gmail folders
List all available folders/labels.
```bash
gmail folders
```
---
## Models & Types
### EmailSummary
Brief email overview (minimal context).
**Fields:**
- `message_id: str` - Unique message ID
- `thread_id: str` - Thread/conversation ID
- `from_: EmailAddress` - Sender
- `to: List[EmailAddress]` - Recipients
- `subject: str` - Email subject
- `date: datetime` - Sent date/time
- `snippet: str` - Short preview (~100 chars)
- `labels: List[str]` - Gmail labels
- `has_attachments: bool` - Has files attached
- `is_unread: bool` - Unread status
**Methods:**
- `to_markdown() -> str` - Formatted output
### EmailFull
Complete email with body (use sparingly).
**Fields:** (All EmailSummary fields plus:)
- `body_plain: str` - Plain text body
- `body_html: str` - HTML body (if exists)
- `attachments: List[Attachment]` - Attached files
- `headers: Dict[str, str]` - All email headers
### EmailAddress
Email address with optional name.
**Fields:**
- `email: str` - Email address
- `name: Optional[str]` - Display name
### SearchResult
Paginated search results.
**Fields:**
- `emails: List[EmailSummary]` - Email summaries
- `total_count: int` - Total matching emails
- `query: str` - Search query used
- `next_page_token: Optional[str]` - Token for next page
**Methods:**
- `to_markdown() -> str` - Formatted output
### Folder
Gmail label/folder info.
**Fields:**
- `id: str` - Label ID
- `name: str` - Label name
- `type: str` - 'system' or 'user'
- `message_count: Optional[int]` - Total messages
- `unread_count: Optional[int]` - Unread messages
### SendEmailRequest
Email sending parameters.
**Fields:**
- `to: List[str]` - Required: recipient emails
- `subject: str` - Required: subject line
- `body: str` - Required: email body
- `cc: Optional[List[str]]` - CC recipients
- `attachments: Optional[List[str]]` - File paths
### SendEmailResponse
Email send result.
**Fields:**
- `success: bool` - Send succeeded
- `message_id: str` - Sent message ID
- `thread_id: str` - Thread ID
- `error: Optional[str]` - Error message if failed
---
## Gmail Search Syntax
### Basic Operators
**From/To:**
```
from:user@example.com # Emails from user
to:user@example.com # Emails to user
cc:user@example.com # CC'd to user
bcc:user@example.com # BCC'd to user
```
**Subject:**
```
subject:invoice # Subject contains "invoice"
subject:(invoice payment) # Subject contains both words
```
**Dates:**
```
after:2024/10/01 # After date
before:2024/10/31 # Before date
older_than:7d # Older than 7 days
newer_than:2d # Newer than 2 days
```
**Status:**
```
is:unread # Unread emails
is:read # Read emails
is:starred # Starred emails
is:important # Marked important
```
**Content:**
```
has:attachment # Has attachments
has:drive # Has Google Drive attachment
has:document # Has document attachment
has:spreadsheet # Has spreadsheet
has:presentation # Has presentation
```
**Size:**
```
size:1000000 # Larger than 1MB
larger:10M # Larger than 10MB
smaller:5M # Smaller than 5MB
```
**Labels:**
```
label:inbox # In INBOX
label:sent # In SENT
-label:inbox # NOT in inbox (archived)
```
### Boolean Operators
```
AND # Both conditions (implicit, can be omitted)
OR # Either condition
- # NOT (exclude)
() # Grouping
```
**Examples:**
```
from:professor@edu AND has:attachment
from:alice OR from:bob
subject:report -from:manager
(from:alice OR from:bob) has:attachment
```
### Advanced Examples
**Unread emails from specific person with attachments:**
```
from:john@example.com is:unread has:attachment
```
**Recent emails about project:**
```
subject:project after:2024/10/01 -label:trash
```
**Important emails not yet read:**
```
is:important is:unread -from:noreply
```
**Large emails with PDFs:**
```
has:attachment filename:pdf larger:5M
```
**Emails in thread:**
```
in:thread_id
```
---
## Quick Reference Card
### Python Library Cheat Sheet
```python
from gmaillm import GmailClient, SendEmailRequest
client = GmailClient()
# List
result = client.list_emails(folder='INBOX', max_results=10)
# Read
email = client.read_email(msg_id, format="summary")
email = client.read_email(msg_id, format="full")
# Search
result = client.search_emails("from:user@example.com has:attachment")
# Thread
thread = client.get_thread(msg_id)
# Send
request = SendEmailRequest(to=["user@example.com"], subject="Hi", body="Hello")
response = client.send_email(request)
# Reply
response = client.reply_email(msg_id, body="Thanks!", reply_all=False)
# Labels
client.modify_labels(msg_id, add_labels=['STARRED'], remove_labels=['UNREAD'])
```
### CLI Cheat Sheet
```bash
gmail verify # Check setup
gmail list --folder INBOX --max 10 # List emails
gmail read <id> --full # Read email
gmail thread <id> # View conversation
gmail search "is:unread" --max 20 # Search
gmail reply <id> --body "Thanks!" # Reply
gmail send --to user@example.com \ # Send
--subject "Test" --body "Hi"
gmail folders # List folders
```
---
## Authentication
Uses existing Gmail MCP OAuth2 credentials:
- **Credentials:** `/Users/wz/.gmail-mcp/credentials.json`
- **OAuth Keys:** `/Users/wz/Desktop/OAuth2/gcp-oauth.keys.json`
Tokens auto-refresh. If authentication fails:
1. Check credential files exist
2. Verify OAuth tokens not expired
3. Run `gmail verify` to diagnose
---
## Common Patterns
### Progressive Disclosure
```python
# Always start with summary
summaries = client.list_emails(max_results=10)
# Only get full content when needed
for summary in summaries.emails:
if "important keyword" in summary.subject.lower():
full = client.read_email(summary.message_id, format="full")
# Process full email
```
### Pagination
```python
all_emails = []
page_token = None
while True:
result = client.list_emails(max_results=50, page_token=page_token)
all_emails.extend(result.emails)
if not result.next_page_token:
break
page_token = result.next_page_token
```
### Error Handling
```python
try:
response = client.send_email(request)
if response.success:
print(f"Sent: {response.message_id}")
else:
print(f"Failed: {response.error}")
except RuntimeError as e:
print(f"Error: {e}")
```
---
## Style Guide System
Located at `references/email-styles/`:
- **STYLE.md** - Precise writing guidelines
- **CLEAR.md** - Brevity guidelines
- **learned/patterns.md** - User-specific patterns (grows over time)
When drafting emails, Claude:
1. Searches sent emails to recipient
2. Extracts patterns (greeting, tone, sign-off)
3. Applies STYLE + CLEAR + learned patterns
4. Shows preview for confirmation
---
## Additional Resources
- **SKILL.md** - Complete usage guide with workflows
- **README.md** - Quick start and installation
- **references/usage_examples.md** - 16 detailed examples
- **references/gmail_search_syntax.md** - Complete search reference

View File

@@ -0,0 +1,404 @@
# Email Styles Guide
Complete guide for creating and managing email styles in gmaillm.
## Overview
Email styles define different writing patterns for various contexts. Each style includes:
- **Metadata** - Name and usage guidance
- **Examples** - Real email templates
- **Guidelines** - Structured writing rules
- **Best practices** - Do's and don'ts
## Quick Start
### List Available Styles
```bash
gmail styles list
```
Shows all styles with "when to use" descriptions.
### View a Style
```bash
gmail styles show professional-formal
```
Displays the complete style template.
### Create a New Style
```bash
gmail styles create my-style
```
Creates from template and opens in your editor.
### Edit Existing Style
```bash
gmail styles edit casual-friend
```
### Validate Styles
```bash
# Validate single style
gmail styles validate my-style
# Auto-fix formatting issues
gmail styles validate my-style --fix
# Validate all styles
gmail styles validate-all --fix
```
## Style File Format
### Complete Structure
Each style file MUST follow this exact structure:
```markdown
---
name: "Style Name"
description: "When to use: Context description (30-200 chars)."
---
<examples>
Example email 1
---
Example email 2
</examples>
<greeting>
- Greeting option 1
- Greeting option 2
</greeting>
<body>
- Body guideline 1
- Body guideline 2
</body>
<closing>
- Closing option 1
- Closing option 2
</closing>
<do>
- Best practice 1
- Best practice 2
</do>
<dont>
- Avoid this 1
- Avoid this 2
</dont>
```
### Required Components
#### 1. YAML Frontmatter
**Required fields:**
- `name` - Style display name (3-50 characters)
- `description` - Usage context (30-200 characters, must start with "When to use:")
**Rules:**
- No extra fields allowed
- Must be at top of file
- Enclosed in `---` markers
**Example:**
```yaml
---
name: "Professional Formal"
description: "When to use: Executives, senior leadership, clients, legal/HR contacts, or first-time professional outreach."
---
```
#### 2. XML Sections
**Required sections (in strict order):**
1. `<examples>` - Example emails showing style in action
2. `<greeting>` - Greeting patterns and guidelines
3. `<body>` - Body content guidelines
4. `<closing>` - Closing patterns
5. `<do>` - Best practices
6. `<dont>` - Things to avoid
**Rules:**
- Must appear in exactly this order
- Each section must have opening and closing tags
- Sections must contain actual content
- Use bullet lists (`- ` followed by space) for guidelines
## Section Details
### Examples Section
**Purpose**: Show complete email examples demonstrating the style.
**Format**:
```markdown
<examples>
Subject: Meeting Follow-up
Hi [Name],
Thanks for meeting today. I'll send the proposal by Friday.
Best,
[Your Name]
---
Subject: Quick Question
Hi [Name],
Do you have 5 minutes to discuss the project timeline?
Thanks,
[Your Name]
</examples>
```
**Requirements:**
- 1-3 complete email examples
- Separate multiple examples with `---`
- Include realistic greetings, body, and closings
### Greeting Section
**Purpose**: Define greeting patterns.
**Format**:
```markdown
<greeting>
- "Dear [Title] [Last Name],"
- Use full name and title for first contact
- Avoid first names unless invited
</greeting>
```
### Body Section
**Purpose**: Define body content guidelines.
**Format**:
```markdown
<body>
- Write concise sentences
- One main point per paragraph
- Use bullet points for lists
- Professional tone throughout
</body>
```
### Closing Section
**Purpose**: Define closing patterns.
**Format**:
```markdown
<closing>
- "Best regards,"
- "Sincerely,"
- Sign with full name and title
</closing>
```
### Do Section
**Purpose**: Best practices to follow.
**Format**:
```markdown
<do>
- Proofread before sending
- Keep paragraphs short
- Use active voice
- Include clear call to action
</do>
```
**Requirements:**
- Minimum 2 items
- Actionable advice
- Clear and specific
### Dont Section
**Purpose**: Things to avoid.
**Format**:
```markdown
<dont>
- Use slang or casual language
- Write overly long paragraphs
- Forget to proofread
- Use all caps for emphasis
</dont>
```
**Requirements:**
- Minimum 2 items
- Clear antipatterns
- Specific examples
## Validation Rules
The `StyleLinter` enforces these rules:
### YAML Frontmatter
- ✓ Required fields: `name`, `description`
- ✓ Name length: 3-50 characters
- ✓ Description: 30-200 characters
- ✓ Description must start with "When to use:"
- ✓ No extra fields
### XML Sections
- ✓ All 6 sections present
- ✓ Correct order: examples → greeting → body → closing → do → dont
- ✓ Proper opening/closing tags
- ✓ Non-empty content
### Formatting
- ✓ No trailing whitespace
- ✓ List items: `- ` (dash + space)
- ✓ Minimum items: examples (1), do (2), dont (2)
### Auto-Fix Capabilities
The `--fix` flag can automatically correct:
- Trailing whitespace
- List item spacing (`-item``- item`)
- Extra blank lines
**Cannot auto-fix:**
- Missing sections
- Wrong section order
- Invalid frontmatter
- Empty sections
## Creating a New Style
### Step 1: Create Template
```bash
gmail styles create my-custom-style
```
This creates `~/.gmaillm/email-styles/my-custom-style.md` with template structure.
### Step 2: Edit in Your Editor
The command automatically opens the file in your default editor (determined by `$EDITOR` environment variable).
### Step 3: Fill In Content
Replace template placeholders with your content:
1. **Update frontmatter** - Set name and description
2. **Add examples** - Write 1-3 complete email examples
3. **Define greeting patterns** - Specify greeting guidelines
4. **Define body guidelines** - Specify writing rules
5. **Define closing patterns** - Specify closing guidelines
6. **List do's** - Best practices (minimum 2)
7. **List dont's** - Things to avoid (minimum 2)
### Step 4: Validate
```bash
gmail styles validate my-custom-style
```
Fix any errors shown.
### Step 5: Use
```bash
gmail styles show my-custom-style
```
## Common Validation Errors
### "Description must start with 'When to use:'"
**Problem**: Description doesn't have required prefix.
**Fix**:
```yaml
# Wrong
description: "For casual emails to friends"
# Correct
description: "When to use: Casual emails to friends and close colleagues."
```
### "Sections must appear in strict order"
**Problem**: Sections are out of order.
**Fix**: Reorder sections to match: examples → greeting → body → closing → do → dont
### "Missing required section"
**Problem**: One or more sections are missing.
**Fix**: Add all 6 required sections with proper tags.
### "List items must start with '- '"
**Problem**: List items have incorrect formatting.
**Fix**:
```markdown
# Wrong
<do>
-Item 1
* Item 2
</do>
# Correct
<do>
- Item 1
- Item 2
</do>
```
## Tips for Good Styles
1. **Be specific** - "Use first name only" not "Be casual"
2. **Show examples** - Real email examples are most helpful
3. **Keep it concise** - Shorter guidelines are easier to follow
4. **Test it** - Use the style for real emails and refine
5. **Version control** - Styles are just text files, commit them to git
## File Location
All styles are stored in:
```
~/.gmaillm/email-styles/
├── professional-formal.md
├── professional-friendly.md
├── academic.md
├── casual-friend.md
├── brief-update.md
└── my-custom-style.md
```
## Built-in Styles
gmaillm includes 5 professional styles:
1. **professional-formal** - Executives, legal, formal outreach
2. **professional-friendly** - Colleagues, known contacts
3. **academic** - Faculty, academic collaborators
4. **casual-friend** - Friends, informal communication
5. **brief-update** - Quick status updates
View any style: `gmail styles show <name>`

View File

@@ -0,0 +1,623 @@
# Gmail Search Syntax Reference
Complete reference for Gmail search operators. Use these with the `gmail search` command.
## Quick Start
```bash
# Basic search
gmail search "from:user@example.com"
# Combined search
gmail search "from:user@example.com has:attachment after:2024/10/01"
# Complex search
gmail search "(from:alice OR from:bob) subject:report -is:read"
```
---
## Basic Operators
### From/To/CC/BCC
```
from:sender@example.com # Emails from sender
to:recipient@example.com # Emails to recipient
cc:person@example.com # CC'd to person
bcc:person@example.com # BCC'd to person (only sent emails)
```
**Examples:**
```bash
# All emails from professor
gmail search "from:professor@university.edu" --max 20
# All emails to colleague
gmail search "to:colleague@company.com" --max 10
# Emails CC'd to manager
gmail search "cc:manager@company.com" --max 5
```
### Subject
```
subject:keyword # Subject contains keyword
subject:"exact phrase" # Subject contains exact phrase
subject:(word1 word2) # Subject contains both words
```
**Examples:**
```bash
# Emails about meetings
gmail search "subject:meeting" --max 10
# Exact subject phrase
gmail search 'subject:"Weekly Report"' --max 5
# Subject with multiple keywords
gmail search "subject:(project deadline)" --max 10
```
### Body Content
```
keyword # Body or subject contains keyword
"exact phrase" # Body or subject has exact phrase
```
**Examples:**
```bash
# Emails mentioning budget
gmail search "budget" --max 10
# Exact phrase in email
gmail search '"quarterly results"' --max 5
```
---
## Date Operators
### Absolute Dates
```
after:YYYY/MM/DD # After specific date
before:YYYY/MM/DD # Before specific date
```
**Examples:**
```bash
# Emails after October 1, 2024
gmail search "after:2024/10/01" --max 20
# Emails before September 30, 2024
gmail search "before:2024/09/30" --max 10
# Emails in date range
gmail search "after:2024/10/01 before:2024/10/31" --max 20
```
### Relative Dates
```
newer_than:Nd # Newer than N days
older_than:Nd # Older than N days
newer_than:Nm # Newer than N months
older_than:Nm # Older than N months
newer_than:Ny # Newer than N years
older_than:Ny # Older than N years
```
**Examples:**
```bash
# Last 7 days
gmail search "newer_than:7d" --max 20
# Older than 30 days
gmail search "older_than:30d" --max 10
# Last 2 months
gmail search "newer_than:2m" --max 20
# Last year
gmail search "newer_than:1y" --max 50
```
---
## Status Operators
### Read/Unread
```
is:read # Read emails
is:unread # Unread emails
```
**Examples:**
```bash
# All unread emails
gmail search "is:unread" --max 20
# Unread emails from specific person
gmail search "from:boss@company.com is:unread" --max 10
```
### Starred/Important
```
is:starred # Starred emails
is:important # Marked important
-is:important # NOT important
```
**Examples:**
```bash
# Starred emails
gmail search "is:starred" --max 20
# Important emails from last week
gmail search "is:important newer_than:7d" --max 10
```
---
## Attachment Operators
### Has Attachment
```
has:attachment # Has any attachment
has:drive # Has Google Drive attachment
has:document # Has document
has:spreadsheet # Has spreadsheet
has:presentation # Has presentation
has:youtube # Has YouTube link
```
**Examples:**
```bash
# All emails with attachments
gmail search "has:attachment" --max 20
# Emails with PDFs
gmail search "filename:pdf" --max 10
# Emails with Google Drive files
gmail search "has:drive" --max 10
```
### Filename
```
filename:name # Attachment filename contains name
filename:pdf # Attachment is PDF
filename:xlsx # Attachment is Excel file
```
**Examples:**
```bash
# Emails with PDF attachments
gmail search "filename:pdf" --max 10
# Specific filename
gmail search 'filename:"report.pdf"' --max 5
# Invoices
gmail search "filename:invoice" --max 20
```
---
## Size Operators
```
size:N # Larger than N bytes
larger:N # Larger than N (use M/K for MB/KB)
smaller:N # Smaller than N
```
**Examples:**
```bash
# Larger than 1MB
gmail search "larger:1M" --max 10
# Larger than 10MB
gmail search "larger:10M" --max 5
# Smaller than 500KB
gmail search "smaller:500K" --max 10
# Large emails with attachments
gmail search "has:attachment larger:5M" --max 10
```
---
## Label Operators
```
label:name # Has specific label
-label:name # Does NOT have label
```
**System labels:**
- `INBOX` - In inbox
- `SENT` - Sent emails
- `DRAFT` - Drafts
- `TRASH` - Trash
- `SPAM` - Spam
- `STARRED` - Starred
- `IMPORTANT` - Important
- `UNREAD` - Unread
- `CATEGORY_PERSONAL` - Personal category
- `CATEGORY_SOCIAL` - Social category
- `CATEGORY_PROMOTIONS` - Promotions category
- `CATEGORY_UPDATES` - Updates category
- `CATEGORY_FORUMS` - Forums category
**Examples:**
```bash
# Emails in inbox
gmail search "label:inbox" --max 20
# Archived emails (not in inbox)
gmail search "-label:inbox" --max 20
# Sent emails
gmail search "label:sent" --max 10
# Custom label
gmail search "label:work" --max 20
```
---
## Boolean Operators
### AND (implicit)
```
keyword1 keyword2 # Both keywords (space = AND)
keyword1 AND keyword2 # Explicit AND
```
**Examples:**
```bash
# Both keywords
gmail search "project deadline" --max 10
# Explicit AND
gmail search "project AND deadline" --max 10
```
### OR
```
keyword1 OR keyword2 # Either keyword
```
**Examples:**
```bash
# Emails from either person
gmail search "from:alice@example.com OR from:bob@example.com" --max 10
# Multiple subjects
gmail search "subject:meeting OR subject:schedule" --max 10
```
### NOT (-)
```
-keyword # Does NOT contain keyword
-operator:value # Does NOT match operator
```
**Examples:**
```bash
# Exclude sender
gmail search "subject:report -from:manager@company.com" --max 10
# Not in inbox (archived)
gmail search "-label:inbox" --max 20
# Not read
gmail search "-is:read" --max 10
```
### Grouping ( )
```
(condition1 OR condition2) # Group conditions
```
**Examples:**
```bash
# Emails from alice OR bob with attachments
gmail search "(from:alice OR from:bob) has:attachment" --max 10
# Multiple subjects with specific date range
gmail search "(subject:meeting OR subject:schedule) after:2024/10/01" --max 20
```
---
## Thread Operators
```
in:thread_id # Emails in specific thread
```
**Example:**
```bash
# Get all emails in a thread (use thread_id from email details)
gmail search "in:19abc123def456" --max 20
```
---
## Wildcard Operator
```
* # Wildcard (limited use in Gmail)
```
**Note:** Gmail's wildcard support is limited. It works best with:
- Email addresses: `from:*@example.com`
- Not recommended for general text searches
---
## Common Search Patterns
### Workflow-Specific Searches
#### Before Composing to Someone
Find all correspondence (sent + received):
```bash
gmail search "to:person@example.com OR from:person@example.com" --max 10
```
#### Finding Unread Important Emails
```bash
gmail search "is:unread is:important" --max 20
```
#### Recent Emails About a Topic
```bash
gmail search "subject:project-name newer_than:30d" --max 10
```
#### Emails from Team with Attachments
```bash
gmail search "(from:alice@team.com OR from:bob@team.com) has:attachment" --max 10
```
#### Large Emails to Clean Up
```bash
gmail search "larger:10M older_than:1y" --max 20
```
#### Unanswered Emails
```bash
gmail search "is:unread from:important@person.com newer_than:7d" --max 10
```
---
## Advanced Search Patterns
### Finding Email Threads
Search for initial email and use thread view:
```bash
# Find thread starter
gmail search "subject:keyword from:person@example.com" --max 5
# Then use thread command
gmail thread <message_id>
```
### Combining Multiple Criteria
```bash
# Complex search: unread emails from professor with attachments in last 30 days
gmail search "from:professor@edu.edu is:unread has:attachment newer_than:30d" --max 10
# Emails from multiple people about specific topic
gmail search "(from:alice OR from:bob) subject:budget newer_than:7d" --max 10
```
### Excluding Common Patterns
```bash
# Important emails excluding automated notifications
gmail search "is:important -from:noreply -from:no-reply" --max 20
# Emails with attachments excluding newsletters
gmail search "has:attachment -label:promotions" --max 20
```
---
## Search Best Practices
### 1. Start Broad, Then Refine
```bash
# Start broad
gmail search "project" --max 20
# Refine
gmail search "project from:alice@example.com" --max 10
# Further refine
gmail search "project from:alice@example.com after:2024/10/01" --max 5
```
### 2. Use Date Ranges for Context
```bash
# Recent context (last 7 days)
gmail search "to:person@example.com newer_than:7d" --max 5
# Historical context (last 6 months)
gmail search "to:person@example.com newer_than:6m" --max 20
```
### 3. Combine Sender and Recipient
```bash
# All correspondence with someone
gmail search "to:person@example.com OR from:person@example.com" --max 10
```
### 4. Use Labels for Organization
```bash
# Search within labeled emails
gmail search "label:work subject:report" --max 10
# Exclude certain labels
gmail search "has:attachment -label:spam -label:trash" --max 20
```
---
## CLI-Specific Options
### Max Results
```bash
# Limit results (1-50)
gmail search "query" --max 10
gmail search "query" --max 20
gmail search "query" --max 50
```
### Folder Filtering
```bash
# Search within specific folder
gmail search "is:unread" --folder INBOX --max 10
gmail search "keyword" --folder SENT --max 20
```
---
## Common Mistakes
### 1. Not Quoting Phrases
**Wrong:**
```bash
gmail search "subject:meeting notes" # Searches for subject:meeting AND notes anywhere
```
**Right:**
```bash
gmail search 'subject:"meeting notes"' # Searches for exact phrase in subject
```
### 2. Forgetting OR is Uppercase
**Wrong:**
```bash
gmail search "from:alice or from:bob" # "or" treated as keyword
```
**Right:**
```bash
gmail search "from:alice OR from:bob" # OR is operator
```
### 3. Using Wildcards for General Text
**Wrong:**
```bash
gmail search "meet*" # Limited wildcard support
```
**Right:**
```bash
gmail search "meeting" # Use complete words
```
### 4. Not Using Parentheses for Complex Queries
**Wrong:**
```bash
gmail search "from:alice OR from:bob has:attachment" # Ambiguous
```
**Right:**
```bash
gmail search "(from:alice OR from:bob) has:attachment" # Clear grouping
```
---
## Quick Reference Table
| Operator | Description | Example |
|----------|-------------|---------|
| `from:` | From sender | `from:user@example.com` |
| `to:` | To recipient | `to:user@example.com` |
| `subject:` | Subject contains | `subject:meeting` |
| `after:` | After date | `after:2024/10/01` |
| `before:` | Before date | `before:2024/10/31` |
| `newer_than:` | Newer than N days/months/years | `newer_than:7d` |
| `older_than:` | Older than N days/months/years | `older_than:30d` |
| `is:unread` | Unread emails | `is:unread` |
| `is:starred` | Starred emails | `is:starred` |
| `has:attachment` | Has attachment | `has:attachment` |
| `filename:` | Attachment filename | `filename:pdf` |
| `larger:` | Larger than size | `larger:10M` |
| `smaller:` | Smaller than size | `smaller:500K` |
| `label:` | Has label | `label:inbox` |
| `-` | NOT operator | `-from:noreply` |
| `OR` | OR operator | `from:alice OR from:bob` |
| `( )` | Grouping | `(from:a OR from:b) subject:x` |
---
## Testing Searches
Always test searches with small result sets first:
```bash
# Test with --max 5 first
gmail search "complex query here" --max 5
# If results look good, increase
gmail search "complex query here" --max 20
```
---
## Pagination
For large result sets, use pagination:
```bash
# Get first page
gmail search "query" --max 50
# Use next_page_token from results for subsequent pages
# (Python API supports this; CLI shows truncated results)
```
---
## Additional Resources
- Gmail search operators: https://support.google.com/mail/answer/7190
- gmaillm API reference: `references/api-reference.md`

View File

@@ -0,0 +1,383 @@
# Gmail Assistant Quick Reference
This file provides quick examples for common gmaillm operations. Load this when you need concrete syntax examples.
## Email Sending Examples
### Basic Send
```bash
gmail send \
--to "recipient@example.com" \
--subject "Subject line" \
--body "Email body content"
```
### Send with CC and BCC
```bash
gmail send \
--to "person1@example.com,person2@example.com" \
--cc "cc@example.com" \
--bcc "bcc@example.com" \
--subject "Subject" \
--body "Body"
```
### Send to Group
```bash
gmail send \
--to "#group-name" \
--subject "Broadcast message" \
--body "Message to entire group"
```
### Send with Attachments
```bash
gmail send \
--to "recipient@example.com" \
--subject "Files attached" \
--body "See attachments" \
--attachments "file1.pdf,file2.jpg"
```
## Search Examples
### Search by Subject
```bash
gmail search "subject:keyword" --max 10
```
### Search by Sender
```bash
gmail search "from:person@example.com" --max 5
```
### Search by Date Range
```bash
gmail search "after:2025/01/01 before:2025/12/31"
```
### Complex Search
```bash
gmail search "from:person subject:project has:attachment" --max 5
```
### Search Unread
```bash
gmail search "is:unread" --max 20
```
## Reading Emails
### Read Summary
```bash
gmail read <message_id>
```
### Read Full Content
```bash
gmail read <message_id> --full
```
### Read Entire Thread
```bash
gmail thread <message_id>
```
### JSON Output for Parsing
```bash
gmail read <message_id> --output-format json
```
## Group Management
### List Groups
```bash
gmail groups list
```
### Show Group Details
```bash
gmail groups show "#group-name"
```
### Create Group
```bash
gmail groups create \
--name "#new-group" \
--emails "person1@example.com,person2@example.com,person3@example.com"
```
### Add Member to Group
```bash
gmail groups add "#group-name" "newperson@example.com"
```
### Remove Member
```bash
gmail groups remove "#group-name" "person@example.com"
```
### Validate Group
```bash
gmail groups validate "#group-name"
```
## Style Management
### List All Styles
```bash
gmail styles list
```
### Show Style Content
```bash
gmail styles show <style-name>
```
### Create New Style
```bash
gmail styles create --name "my-style"
# Opens editor for you to define the style
```
### Edit Existing Style
```bash
gmail styles edit <style-name>
```
### Validate Style Format
```bash
gmail styles validate <style-name>
```
### Validate All Styles
```bash
gmail styles validate-all
```
## Workflow Management
### List Workflows
```bash
gmail workflows list
```
### Show Workflow Details
```bash
gmail workflows show <workflow-id>
```
### Create Workflow
```bash
gmail workflows create \
--id "daily-review" \
--name "Daily Email Review" \
--query "is:unread -label:spam" \
--auto-mark-read
```
### Run Workflow
```bash
gmail workflows run <workflow-id>
```
### Run Ad-hoc Query
```bash
gmail workflows run --query "is:unread from:important@person.com"
```
## Gmail Query Syntax
Common Gmail search operators:
| Operator | Example | Description |
|----------|---------|-------------|
| `from:` | `from:alice@example.com` | Emails from sender |
| `to:` | `to:bob@example.com` | Emails to recipient |
| `subject:` | `subject:meeting` | Subject contains word |
| `is:unread` | `is:unread` | Unread emails |
| `is:read` | `is:read` | Read emails |
| `has:attachment` | `has:attachment` | Has attachments |
| `label:` | `label:important` | Has label |
| `after:` | `after:2025/01/01` | After date (YYYY/MM/DD) |
| `before:` | `before:2025/12/31` | Before date |
| `newer_than:` | `newer_than:7d` | Last N days (d/m/y) |
| `older_than:` | `older_than:1m` | Older than N time |
| `OR` | `from:alice OR from:bob` | Either condition |
| `-` | `-label:spam` | Exclude (NOT) |
**Combine operators:**
```bash
gmail search "from:boss subject:urgent is:unread"
```
## Email Style Format
Email styles use YAML frontmatter + XML-like sections:
```markdown
---
name: "style-name"
description: "When to use: Context description (30-200 chars)."
---
<examples>
Example 1
---
Example 2
</examples>
<greeting>
- "Hi [Name],"
</greeting>
<body>
- Guideline 1
- Guideline 2
</body>
<closing>
- "Best,"
</closing>
<do>
- Best practice 1
</do>
<dont>
- What to avoid
</dont>
```
Required sections in strict order: examples → greeting → body → closing → do → dont
## Common Email Workflows
### 1. Research + Draft + Send
```bash
# Search for similar emails
gmail search "subject:similar topic" --max 3
# Read one for context
gmail read <message_id> --full
# Check style
gmail styles show professional-formal
# TEST first
gmail send --to fuchengwarrenzhu@gmail.com --subject "[TEST] ..." --body "..."
# Send for real
gmail send --to real@email.com --subject "..." --body "..." --yolo
```
### 2. Bulk Processing with Workflow
```bash
# Create workflow for common query
gmail workflows create \
--id "newsletter-cleanup" \
--name "Clean Up Newsletters" \
--query "label:newsletters is:read older_than:30d"
# Run workflow
gmail workflows run newsletter-cleanup
```
### 3. Group Broadcast
```bash
# Verify group
gmail groups show "#team"
# Check style
gmail styles show posts
# TEST
gmail send --to fuchengwarrenzhu@gmail.com --subject "[TEST] Update" --body "..."
# Broadcast
gmail send --to "#team" --subject "Update" --body "..." --yolo
```
## Status and Configuration
### Check Account Status
```bash
gmail status
```
### Verify Authentication
```bash
gmail verify
```
### Show Configuration
```bash
gmail config show
```
### List Labels
```bash
gmail labels list
```
## JSON Output for Automation
All commands support `--output-format json` for programmatic parsing:
```bash
# Get JSON for parsing
gmail search "is:unread" --output-format json | jq '.emails[] | {from: .from_.email, subject: .subject}'
# List groups in JSON
gmail groups list --output-format json
# Read email as JSON
gmail read <message_id> --output-format json
```
## Common Gotchas
1. **Email IDs**: Displayed short (12 chars) but use full ID in commands
2. **Group prefix**: Always use `#` prefix (e.g., `#team` not `team`)
3. **YOLO flag**: Skips confirmation, use after testing
4. **Date format**: Use YYYY/MM/DD for Gmail queries
5. **Test emails**: ALWAYS test to fuchengwarrenzhu@gmail.com first
6. **Style order**: Sections must be in exact order (examples, greeting, body, closing, do, dont)
7. **Attachment paths**: Use absolute or relative file paths, comma-separated