Skip to main content

@idiomark/adapter-outlook

Outlook/Microsoft 365 adapter for the Idiomark. This adapter fetches data from Microsoft 365 using the Microsoft Graph API for personality analysis.

Features​

  • Email Analysis: Fetches sent, received, and draft emails with full content and metadata
  • Calendar Insights: Retrieves calendar events, meetings, and appointments
  • Contact Network: Imports contacts with professional and personal information
  • Task Management: Analyzes Outlook tasks and Microsoft Todo items
  • Rich Metadata: Extracts categories, flags, importance levels, and more

Personality Signals​

This adapter extracts personality-relevant data from:

Email Writing Style​

  • Formality: Word count, sentence structure, and punctuation patterns
  • Response Patterns: Email frequency, reply times, and threading behavior
  • Tone Analysis: Subject lines, greetings, and sign-offs
  • Organization: Use of folders, categories, and rules

Calendar Organization​

  • Planning Horizon: How far in advance events are scheduled
  • Time Preferences: Preferred meeting times and days
  • Meeting Patterns: One-on-one vs. group meetings frequency
  • Punctuality: Meeting attendance and response patterns

Task Management​

  • Completion Rate: Ratio of completed to active tasks
  • Priority Handling: Distribution of high/medium/low priority tasks
  • Follow-through: Task aging and overdue patterns
  • Organizational Style: Use of categories and reminders

Communication Preferences​

  • Directness: Email length and complexity
  • Network Size: Contact count and distribution
  • Professional vs. Personal: Balance of work and personal connections
  • Responsiveness: Average response times

Installation​

npm install @idiomark/adapter-outlook
# or
pnpm add @idiomark/adapter-outlook
# or
yarn add @idiomark/adapter-outlook

Authentication​

This adapter uses OAuth 2.0 access tokens for authentication with Microsoft Graph API.

Getting an Access Token​

  1. Register your application in Azure Portal

    • Navigate to Azure Active Directory > App registrations
    • Create a new registration
    • Note the Application (client) ID
  2. Configure API permissions:

    • Add Microsoft Graph permissions
    • Delegated permissions (for user data):
      • Mail.Read
      • Mail.ReadWrite
      • Calendar.Read
      • Contacts.Read
      • Tasks.Read
      • Tasks.ReadWrite
    • Or Application permissions for service-to-service
  3. Get an access token using your preferred OAuth flow:

    • Authorization Code Flow (recommended for web apps)
    • Client Credentials Flow (for background services)
    • Device Code Flow (for CLI tools)

Using the Adapter​

import { OutlookAdapter } from '@idiomark/adapter-outlook'

const adapter = new OutlookAdapter({
accessToken: 'your-oauth2-access-token',
userId: 'optional-user-id', // Will be fetched automatically
tenantId: 'optional-tenant-id' // For multi-tenant scenarios
})

// Authenticate
const isAuthenticated = await adapter.authenticate()

if (!isAuthenticated) {
console.error('Authentication failed')
}

Usage​

Basic Usage​

import { OutlookAdapter, type OutlookFetchOptions } from '@idiomark/adapter-outlook'

const adapter = new OutlookAdapter({
accessToken: process.env.MICROSOFT_ACCESS_TOKEN!
})

// Fetch data with default options
const data = await adapter.fetchData({
limit: 200,
includeReplies: true
})

// Extract raw text with personality insights
const result = await adapter.extractRawText({
limit: 200,
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31'),
includeSentEmails: true,
includeReceivedEmails: true,
includeCalendar: true,
includeContacts: true,
includeTasks: true,
includeTodo: true
})

console.log(result.metadata.personalityInsights)

Advanced Options​

const options: OutlookFetchOptions = {
// General options
limit: 500,
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31'),
includeReplies: true,

// Outlook-specific options
includeSentEmails: true, // Fetch sent emails
includeReceivedEmails: true, // Fetch received emails
includeCalendar: true, // Fetch calendar events
includeContacts: true, // Fetch contacts
includeTasks: true, // Fetch Outlook tasks
includeTodo: true, // Fetch Microsoft Todo items
includeDrafts: false, // Include draft emails
folderNames: [], // Specific mail folders
categories: [] // Filter by categories
}

const data = await adapter.fetchData(options)

Individual Data Fetching​

You can also fetch specific types of data:

// Fetch only sent emails
const sentEmails = await adapter.fetchSentEmails({
limit: 100,
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31')
})

// Fetch calendar events
const events = await adapter.fetchEvents({
limit: 50,
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31')
})

// Fetch contacts
const contacts = await adapter.fetchContacts({
limit: 200
})

// Fetch tasks
const tasks = await adapter.fetchTasks({
limit: 50,
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31')
})

// Fetch inbox rules (organizational patterns)
const rules = await adapter.fetchInboxRules()

// Fetch categories (how user organizes information)
const categories = await adapter.fetchCategories()

Health Check​

const health = await adapter.healthCheck()
console.log(health)
// { healthy: true, latency: 245 }

Getting Metrics​

const metrics = adapter.getMetrics()
console.log(metrics)
// {
// requests: 45,
// cacheHits: 1,
// cacheMisses: 0,
// retries: 0,
// errors: 0,
// avgLatency: 0
// }

Data Returned​

Each data item includes:

  • id: Unique identifier
  • **type`: Content type (email, event, contact, task, todo)
  • text: Text content for analysis
  • created_at: Creation timestamp
  • author: Author information
  • metrics: Engagement metrics (when available)
  • metadata: Platform-specific metadata

Email Metadata​

{
subject: string
importance: 'low' | 'normal' | 'high'
isRead: boolean
isDraft: boolean
hasAttachments: boolean
from: string
sender: string
toRecipients: string
ccRecipients: string
bccRecipients: string
sentDateTime: string
receivedDateTime: string
conversationId: string
webLink: string
wordCount: number
sentenceCount: number
}

Event Metadata​

{
subject: string
location: string
isAllDay: boolean
showAs: string
importance: string
start: string
end: string
duration: number // minutes
attendeeCount: number
attendees: string
isOrganizer: boolean
responseRequested: boolean
recurrence: string
webLink: string
onlineMeetingUrl: string
}

Task Metadata​

{
title: string
status: 'notStarted' | 'inProgress' | 'completed' | 'waitingOnOthers' | 'deferred'
importance: string
dueDateTime: string
startDateTime: string
completedDateTime: string
hasAttachments: boolean
isReminderOn: boolean
recurrence: string
}

Personality Insights​

The adapter automatically calculates personality insights:

{
emailStyle: {
avgWordCount: 45,
avgSentenceCount: 3,
formalityScore: 0.7,
responsePattern: 'frequent' // 'frequent' | 'moderate' | 'selective'
},
calendarOrganization: {
avgMeetingsPerDay: 3.2,
preferredMeetingTimes: ['9:00', '10:00', '14:00'],
planningHorizon: 'long-term' // 'long-term' | 'medium-term' | 'short-term'
},
taskManagement: {
completionRate: 85,
priorityPattern: 'balanced',
organizationalStyle: 'highly-organized'
},
communicationPreferences: {
directness: 0.6,
emailFrequency: 'moderate',
contactNetworkSize: 234
}
}

Rate Limiting​

Microsoft Graph API has generous rate limits:

  • Delegated permissions: 20,000 requests per 10 minutes
  • Application permissions: 10,000 requests per 10 minutes

This adapter automatically handles rate limiting with:

  • Request throttling when approaching limits
  • Automatic retry with exponential backoff
  • Proper handling of 429 (Too Many Requests) responses

Error Handling​

try {
const data = await adapter.fetchData()
} catch (error) {
if (error.message.includes('authentication')) {
// Handle auth errors
} else if (error.message.includes('rate limit')) {
// The adapter handles this automatically
} else {
console.error('Error:', error)
}
}

API Reference​

OutlookAdapter​

Constructor​

constructor(auth: OutlookAuth)

Methods​

  • authenticate(): Promise<boolean> - Authenticate with Microsoft Graph API
  • fetchData(options): Promise<RawContent[]> - Fetch all data
  • normalize(raw): NormalizedContent - Normalize content to standard format
  • extractRawText(options): Promise<OutlookAdapterOutput> - Extract text with personality insights
  • fetchUserProfile(): Promise<OutlookUser | null> - Fetch user profile
  • fetchSentEmails(options): Promise<OutlookMessage[]> - Fetch sent emails
  • fetchReceivedEmails(options): Promise<OutlookMessage[]> - Fetch received emails
  • fetchDrafts(options): Promise<OutlookMessage[]> - Fetch draft emails
  • fetchEvents(options): Promise<OutlookEvent[]> - Fetch calendar events
  • fetchContacts(options): Promise<OutlookContact[]> - Fetch contacts
  • fetchTasks(options): Promise<OutlookTask[]> - Fetch tasks
  • fetchTodoTasks(options): Promise<OutlookTodoTask[]> - Fetch todo items
  • fetchInboxRules(): Promise<OutlookRule[]> - Fetch inbox rules
  • fetchCategories(): Promise<OutlookCategory[]> - Fetch categories
  • healthCheck(): Promise<object> - Check adapter health
  • getMetrics(): object - Get usage metrics
  • reset(): Promise<void> - Reset cached data
  • dispose(): Promise<void> - Dispose of resources

Type Definitions​

interface OutlookAuth {
accessToken: string
userId?: string
tenantId?: string
}

interface OutlookFetchOptions extends FetchOptions {
includeSentEmails?: boolean
includeReceivedEmails?: boolean
includeCalendar?: boolean
includeContacts?: boolean
includeTasks?: boolean
includeTodo?: boolean
includeDrafts?: boolean
folderNames?: string[]
categories?: string[]
}

interface OutlookAdapterOutput {
rawContent: string[]
metadata: {
sampleSize: number
timeframe: { from: string; to: string }
sources: string[]
personalityInsights?: PersonalityInsights
}
}

Examples​

Example 1: Analyze Email Writing Style​

import { OutlookAdapter } from '@idiomark/adapter-outlook'

const adapter = new OutlookAdapter({ accessToken: token })
await adapter.authenticate()

// Fetch only sent emails for writing style analysis
const emails = await adapter.fetchSentEmails({ limit: 200 })

// Calculate writing metrics
const totalWords = emails.reduce((sum, email) => {
const text = email.body?.content || ''
return sum + text.split(/\s+/).length
}, 0)

const avgWordsPerEmail = totalWords / emails.length
console.log(`Average: ${avgWordsPerEmail} words per email`)

Example 2: Calendar Organization Analysis​

// Fetch calendar events for the past year
const events = await adapter.fetchEvents({
limit: 100,
startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000),
endDate: new Date()
})

// Analyze meeting patterns
const hourCounts: Record<number, number> = {}
events.forEach(event => {
if (event.start?.dateTime) {
const hour = new Date(event.start.dateTime).getHours()
hourCounts[hour] = (hourCounts[hour] || 0) + 1
}
})

console.log('Meeting frequency by hour:', hourCounts)

Example 3: Task Completion Rate​

// Fetch tasks
const tasks = await adapter.fetchTasks({ limit: 100 })

// Calculate completion rate
const completed = tasks.filter(t => t.status === 'completed').length
const rate = (completed / tasks.length) * 100

console.log(`Task completion rate: ${rate.toFixed(1)}%`)

Microsoft Graph API Documentation​

License​

MIT

Contributing​

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

Support​

For issues and questions: