@idiomark/adapter-gmail
Gmail adapter for the Personality Collection Protocol (Idiomark). This adapter extracts email communications, threads, drafts, and organizational patterns from Gmail accounts for personality analysis.
Features
- Email Extraction: Fetches sent emails, received emails, and drafts
- Thread Analysis: Analyzes email threads for conversation patterns
- Label Organization: Extracts user-defined labels for organizational preference analysis
- Personality Signals: Detects communication patterns, writing style, and interaction preferences
- OAuth2 Authentication: Secure authentication with Gmail API
- Rate Limiting: Respects Gmail's 250 quota units per day limit
Installation
pnpm install @idiomark/adapter-gmail
Authentication
This adapter requires a Gmail OAuth2 access token. You'll need to:
- Create a project in Google Cloud Console
- Enable the Gmail API
- Create OAuth 2.0 credentials
- Obtain an access token
Setting up OAuth2
Follow the Gmail API authentication guide to set up OAuth2 authentication.
Usage
Basic Usage
import { GmailAdapter } from '@idiomark/adapter-gmail'
// Initialize with OAuth2 access token
const adapter = new GmailAdapter({
accessToken: 'your-oauth2-access-token'
})
// Authenticate (optional - will happen automatically on first request)
const authenticated = await adapter.authenticate()
if (!authenticated) {
console.error('Authentication failed')
}
// Fetch data for personality analysis
const content = await adapter.fetchData({
limit: 100,
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31'),
includeReplies: true
})
// Normalize content
const normalized = content.map(item => adapter.normalize(item))
Advanced Usage
// Fetch specific types of content
const sentMessages = await adapter.fetchMessages({
query: 'in:sent',
limit: 50,
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31')
})
const threads = await adapter.fetchThreads({
query: 'in:inbox',
limit: 20
})
const drafts = await adapter.fetchDrafts({ limit: 10 })
const labels = await adapter.fetchLabels()
// Extract personality signals
const signals = adapter.extractPersonalitySignals(sentMessages, threads)
console.log('Writing style:', signals.writingStyle)
console.log('Communication patterns:', signals.communicationPatterns)
Parsing Message Content
// Parse individual message for detailed analysis
const message = await adapter.fetchMessageById('message-id')
const parsed = adapter.parseMessageContent(message)
console.log('From:', parsed.from)
console.log('To:', parsed.to)
console.log('Subject:', parsed.subject)
console.log('Body:', parsed.bodyPlain)
console.log('Signature:', parsed.signature)
console.log('Attachments:', parsed.attachments)
API Reference
GmailAdapter
Constructor
constructor(auth: GmailAuth)
Parameters:
auth.accessToken: OAuth2 access token for Gmail APIauth.userId: User ID (default:'me'for authenticated user)
Methods
authenticate()
Authenticates with Gmail and fetches user profile.
async authenticate(): Promise<boolean>
Returns: true if authentication succeeded, false otherwise
fetchData(options)
Fetches all relevant data for personality analysis.
async fetchData(options: FetchOptions): Promise<RawContent[]>
Parameters:
options.limit: Maximum number of items to fetch (default: 100)options.startDate: Start date for filtering messagesoptions.endDate: End date for filtering messagesoptions.includeReplies: Whether to include received messages (default: true)
Returns: Array of raw content items
fetchMessages(options)
Fetches messages with optional query.
async fetchMessages(options: {
query?: string
limit?: number
startDate?: Date
endDate?: Date
pageToken?: string
}): Promise<GmailMessage[]>
Query Examples:
in:sent- Messages in Sent folderin:inbox- Messages in Inboxis:unread- Unread messageshas:attachment- Messages with attachmentsfrom:example@gmail.com- Messages from specific sendersubject:important- Messages with specific subject
fetchThreads(options)
Fetches email threads for conversation analysis.
async fetchThreads(options: {
query?: string
limit?: number
startDate?: Date
endDate?: Date
pageToken?: string
}): Promise<GmailThread[]>
fetchDrafts(options)
Fetches draft emails.
async fetchDrafts(options: {
limit?: number
}): Promise<GmailDraft[]>
fetchLabels()
Fetches all user-defined labels.
async fetchLabels(): Promise<GmailLabel[]>
parseMessageContent(message)
Parses a Gmail message to extract structured content.
parseMessageContent(message: GmailMessage): GmailParsedContent | null
Returns: Parsed content including:
from: Sender email addressto: Recipient email addressescc: CC recipientsbcc: BCC recipientssubject: Email subjectbodyPlain: Plain text bodybodyHtml: HTML bodydate: Sent datesignature: Detected signatureattachments: Attachment information
extractPersonalitySignals(messages, threads)
Extracts personality signals from Gmail content.
extractPersonalitySignals(
messages: GmailMessage[],
threads: GmailThread[]
): GmailPersonalitySignals
Returns: Personality signals including:
communicationPatterns: Response times, email frequency, time preferenceswritingStyle: Greeting/closing patterns, formality level, typical lengthinteractionPatterns: Recipients, reply/forward frequencytopicPreferences: Common subjects, keywords, domains
healthCheck()
Checks adapter health and API connectivity.
async healthCheck(): Promise<{
healthy: boolean
latency?: number
error?: string
}>
getMetrics()
Gets current metrics and quota usage.
getMetrics(): {
quotaUsed: number
quotaLimit: number
quotaRemaining: number
requests: number
resetTime: string
}
reset()
Resets cached data.
async reset(): Promise<void>
dispose()
Disposes of resources.
async dispose(): Promise<void>
Personality Signals Detected
Communication Patterns
- Email Frequency: How often the user sends emails
- Time of Day Preferences: When emails are typically sent
- Day of Week Preferences: Which days are most active
- Average Response Time: Time taken to respond to emails
Writing Style
- Greeting Patterns: Common greeting phrases (Hi, Hello, Dear, etc.)
- Closing Patterns: Common closing phrases (Regards, Thanks, etc.)
- Signature Usage: Detected email signatures
- Formality Level: formal, casual, or mixed
- Typical Length: Min, max, and average email length
Interaction Patterns
- To Recipients: People frequently emailed directly
- CC Recipients: People frequently CC'd
- Reply Frequency: How often user replies vs. initiates
- Forward Frequency: How often user forwards emails
- Thread Initiation: Whether user starts or joins conversations
Topic Preferences
- Subjects: Common email subjects
- Common Keywords: Frequently used words
- Domains: Organizations frequently contacted
Rate Limiting
The Gmail API has a quota limit of 250 quota units per day per user. Different operations consume different amounts of quota:
| Operation | Quota Cost |
|---|---|
| Get message | 1 |
| List messages | 1-100 |
| Get thread | 10 |
| List threads | 1-100 |
| Get draft | 5 |
| List drafts | 1-100 |
| Get attachment | 5 |
| Get labels | 1 |
This adapter automatically tracks quota usage and will warn when approaching the limit. If the quota is exhausted, you'll need to wait until midnight (Pacific Time) for the quota to reset.
Error Handling
try {
const content = await adapter.fetchData({ limit: 100 })
} catch (error) {
if (error.message.includes('quota exhausted')) {
console.error('Gmail quota exhausted. Please try again tomorrow.')
} else if (error.message.includes('Authentication failed')) {
console.error('Invalid or expired access token')
} else {
console.error('Error fetching Gmail data:', error.message)
}
}
Types
GmailAuth
interface GmailAuth {
accessToken: string
userId?: string // Default: 'me'
}
GmailProfile
interface GmailProfile {
emailAddress: string
messagesTotal: number
threadsTotal: number
historyId: string
}
GmailMessage
interface GmailMessage {
id: string
threadId: string
labelIds: string[]
snippet: string
historyId: string
internalDate: string
payload?: GmailMessagePayload
sizeEstimate: number
}
GmailThread
interface GmailThread {
id: string
historyId: string
messages: GmailMessage[]
}
GmailPersonalitySignals
See the "Personality Signals Detected" section above for the full structure.
Gmail Query Reference
The adapter supports Gmail's search syntax for filtering messages:
| Query | Description |
|---|---|
in:sent | Messages in Sent folder |
in:inbox | Messages in Inbox |
is:unread | Unread messages |
is:read | Read messages |
is:starred | Starred messages |
has:attachment | Messages with attachments |
from:email@example.com | From specific sender |
to:email@example.com | To specific recipient |
subject:keyword | Subject contains keyword |
after:YYYY/MM/DD | After specific date |
before:YYYY/MM/DD | Before specific date |
label:label-name | Messages with specific label |
For more search operators, see the Gmail search operators documentation.
Privacy and Security
- This adapter requires OAuth2 authentication - never share access tokens
- Email content may contain sensitive information
- Always obtain proper consent before analyzing someone's emails
- Consider anonymizing or redacting sensitive information before storage
- Follow applicable privacy laws (GDPR, CCPA, etc.)
Contributing
Contributions are welcome! Please read the main Idiomark contributing guidelines for details.
License
MIT