Skip to main content

@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:

  1. Create a project in Google Cloud Console
  2. Enable the Gmail API
  3. Create OAuth 2.0 credentials
  4. 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 API
  • auth.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 messages
  • options.endDate: End date for filtering messages
  • options.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 folder
  • in:inbox - Messages in Inbox
  • is:unread - Unread messages
  • has:attachment - Messages with attachments
  • from:example@gmail.com - Messages from specific sender
  • subject: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 address
  • to: Recipient email addresses
  • cc: CC recipients
  • bcc: BCC recipients
  • subject: Email subject
  • bodyPlain: Plain text body
  • bodyHtml: HTML body
  • date: Sent date
  • signature: Detected signature
  • attachments: 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 preferences
  • writingStyle: Greeting/closing patterns, formality level, typical length
  • interactionPatterns: Recipients, reply/forward frequency
  • topicPreferences: 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:

OperationQuota Cost
Get message1
List messages1-100
Get thread10
List threads1-100
Get draft5
List drafts1-100
Get attachment5
Get labels1

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:

QueryDescription
in:sentMessages in Sent folder
in:inboxMessages in Inbox
is:unreadUnread messages
is:readRead messages
is:starredStarred messages
has:attachmentMessages with attachments
from:email@example.comFrom specific sender
to:email@example.comTo specific recipient
subject:keywordSubject contains keyword
after:YYYY/MM/DDAfter specific date
before:YYYY/MM/DDBefore specific date
label:label-nameMessages 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