Skip to content

Meridian Shared Email Processing: Implementation Guide

Date: September 24th, 2025 Author: Daniel Shanklin, Director of AI and Technology, AIC Holdings Tags: Microsoft Graph API, Azure AD Applications, Shared Mailbox Processing, Background Automation

Sources: - Microsoft Graph API Documentation: Official API reference and implementation guides - Azure AD Application Registration: Authentication and permission configuration procedures


The Meridian AI Agent: A Full-Time Digital Employee

The meridian@aicholdings.com shared mailbox serves as the workspace for our first autonomous AI agent implementation. This system represents a practical example of how AI agents can function as dedicated digital employees, processing information continuously without human intervention.

The AI agent operates as a full-time background worker that reads incoming emails, tracks processing status, extracts relevant data, and routes information through established data flows. Unlike traditional automation scripts, this agent maintains context awareness and decision-making capabilities for email content analysis.

Four team members (Slate DeMuth, Luke Huntley, Daniel Shanklin, and Collin Bird) maintain oversight access to the shared mailbox while the AI agent handles routine processing operations. This architecture demonstrates how AI agents can augment human teams rather than replace them.

The implementation provides a template for developing additional AGI agents across AIC Holdings operations. The pattern established with Meridian email processing can extend to document analysis, data validation, and other information processing workflows that currently require manual coordination.

Technical Implementation Overview

The system uses Microsoft Graph API with Azure AD application authentication to provide automated email processing with duplicate prevention. The AI agent processes emails in background operations without requiring user authentication for each execution.

System Architecture Overview

The complete system involves four main components: Azure AD application registration, Microsoft Graph API authentication, shared mailbox access, and email processing logic.

graph TB
    subgraph AzureAD[Azure AD]
        AAD[Azure AD Application<br/>Client ID + Secret]
        Policy[Application Access Policy<br/>meridian mailbox only]
    end

    subgraph GraphAPI_Sub[Microsoft Graph API]
        Token[Access Token Endpoint]
        GraphAPI[Graph API Endpoints<br/>users/mailbox/messages]
    end

    subgraph Office365[Office 365]
        Mailbox[meridian shared mailbox]
        Inbox[Inbox Folder]
        Processed[Processed Folder]
    end

    subgraph AgentProc[AI Agent Processing]
        Agent[Meridian AI Agent<br/>Python/Node.js]
        Logic[Content Analysis<br/>Data Extraction & Routing]
        Storage[Data Flow Integration<br/>Database/Systems]
    end

    AAD --> Token
    Token --> Agent
    Agent --> GraphAPI
    GraphAPI --> Mailbox
    Inbox --> Agent
    Agent --> Processed
    Agent --> Logic
    Logic --> Storage
    Policy --> Mailbox

The architecture uses application permissions rather than delegated permissions to enable fully automated operation without user authentication requirements.

Authentication Flow: Client Credentials vs Delegated Permissions

Microsoft Graph API supports two primary authentication approaches. Understanding the distinction determines whether your system requires interactive user login.

sequenceDiagram
    participant Agent as Meridian AI Agent
    participant AAD as Azure AD
    participant Graph as Graph API
    participant Mailbox as Shared Mailbox

    Note over Agent, Mailbox: Client Credentials Flow (Automated)
    Agent->>AAD: POST /oauth2/v2.0/token<br/>client_id + client_secret
    AAD->>Agent: access_token (no user context)
    Agent->>Graph: GET /users/meridian@aicholdings.com/messages<br/>Authorization: Bearer token
    Graph->>Mailbox: Access with Application permissions
    Mailbox->>Graph: Email data
    Graph->>Agent: JSON response

    Note over Agent, Mailbox: Runs completely automated - no user login required

Client credentials flow provides the access pattern required for background automation. The application authenticates directly with Azure AD using client ID and secret, receiving tokens that work without user context.

Delegated permissions would require user login for each session, making automated processing impractical for background operations. Application permissions grant the registered app direct access to specified resources.

AI Agent Processing Workflow

The Meridian AI agent follows a systematic workflow that demonstrates autonomous decision-making capabilities while maintaining reliable processing patterns.

flowchart TD
    Start([Scheduled Execution]) --> Auth[Authenticate with Azure AD]
    Auth --> Token[Receive Access Token]
    Token --> CheckFolder[Create/Verify Processed Folder]
    CheckFolder --> GetEmails[Retrieve Inbox Messages<br/>GET users/mailbox/messages]

    GetEmails --> HasEmails{Emails Found?}
    HasEmails -->|No| End([Complete])
    HasEmails -->|Yes| ProcessLoop[For Each Email]

    ProcessLoop --> ExtractData[AI Content Analysis<br/>Subject, Body, Attachments, Context]
    ExtractData --> AgentLogic[Agent Decision Making<br/>Classify, Extract, Route Data]
    AgentLogic --> Success{Processing Success?}

    Success -->|Yes| MoveEmail[Move to Processed Folder<br/>POST messages/id/move]
    Success -->|No| LogError[Log Error<br/>Continue to Next Email]

    MoveEmail --> NextEmail{More Emails?}
    LogError --> NextEmail
    NextEmail -->|Yes| ProcessLoop
    NextEmail -->|No| Summary[Generate Processing Summary]
    Summary --> End

The AI agent maintains processing state through folder-based tracking, demonstrating how autonomous systems can implement reliable duplicate prevention. This pattern shows how AI agents can maintain context and operational awareness across multiple execution cycles, a key characteristic of AGI systems.

Technology Stack Options

The implementation can use multiple programming languages depending on team preferences and existing infrastructure.

Python Implementation

Python provides extensive library support for HTTP requests and JSON processing. The requests library handles OAuth2 authentication and Graph API interactions efficiently.

# Example authentication pattern
token_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
token_data = {
    'client_id': client_id,
    'client_secret': client_secret,
    'scope': 'https://graph.microsoft.com/.default',
    'grant_type': 'client_credentials'
}
response = requests.post(token_url, data=token_data)
access_token = response.json()['access_token']

Python advantages include rapid development, extensive documentation, and straightforward JSON handling. The language works well for scripts that don't require high-performance concurrent processing.

Node.js Implementation

Node.js offers native JSON support and asynchronous processing capabilities. Microsoft provides official Graph SDK packages for JavaScript environments.

// Example using Microsoft Graph SDK
const { Client } = require('@azure/msal-node');
const { AuthenticationProvider } = require('@microsoft/microsoft-graph-client');

const clientConfig = {
    auth: {
        clientId: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET,
        authority: `https://login.microsoftonline.com/${process.env.TENANT_ID}`
    }
};

Node.js advantages include asynchronous processing for multiple API calls, official Microsoft SDK support, and JSON-native data handling. The platform scales better for high-volume email processing.

Both implementations support the same Graph API endpoints and authentication patterns. The choice depends on team expertise and integration requirements with existing systems.

Azure AD Application Setup

Luke will need to complete several configuration steps in the Azure Portal to enable automated mailbox access.

Application Registration Steps

  1. Navigate to Azure Portal → Azure Active Directory → App registrations
  2. Click "New registration"
  3. Configure application settings:
  4. Name: "Meridian Email Processor"
  5. Supported account types: "Accounts in this organizational directory only"
  6. Redirect URI: Leave blank for client credentials flow
  7. Record the Application (client) ID and Directory (tenant) ID from the Overview page

Permission Configuration

The application requires specific Microsoft Graph permissions for automated mailbox access:

  1. Navigate to API permissions in the registered application
  2. Click "Add a permission" → Microsoft Graph → Application permissions
  3. Add Mail.ReadWrite permission (not delegated permissions)
  4. Click "Grant admin consent for [organization]" - this step requires tenant administrator privileges

Client Secret Generation

  1. Navigate to Certificates & secrets
  2. Click "New client secret"
  3. Set appropriate expiration period (recommend 24 months for production systems)
  4. Copy the secret value immediately - this value is not retrievable after leaving the page

Exchange Online Access Policy

The application access policy restricts the registered app to specific mailboxes, preventing broader organizational email access:

# Connect to Exchange Online (requires Exchange administrator role)
Connect-ExchangeOnline

# Create restrictive access policy
New-ApplicationAccessPolicy -AppId "APPLICATION_CLIENT_ID" -PolicyScopeGroupId "meridian@aicholdings.com" -AccessRight RestrictAccess -Description "Restrict Meridian email processor to designated shared mailbox only"

# Verify policy creation
Get-ApplicationAccessPolicy

This policy ensures the application can only access the meridian@aicholdings.com mailbox, regardless of other organizational permissions.

API Implementation Examples

The Microsoft Graph API provides consistent endpoints across different programming languages. Here are practical examples for common operations.

Authentication Token Retrieval

# Python implementation
import requests

def get_access_token(tenant_id, client_id, client_secret):
    url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': 'https://graph.microsoft.com/.default',
        'grant_type': 'client_credentials'
    }
    response = requests.post(url, data=data)
    return response.json()['access_token']
// Node.js implementation
const axios = require('axios');

async function getAccessToken(tenantId, clientId, clientSecret) {
    const url = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
    const data = new URLSearchParams({
        'client_id': clientId,
        'client_secret': clientSecret,
        'scope': 'https://graph.microsoft.com/.default',
        'grant_type': 'client_credentials'
    });

    const response = await axios.post(url, data);
    return response.data.access_token;
}

Email Retrieval and Processing

# Retrieve inbox messages with filtering
def get_inbox_messages(access_token, mailbox, limit=50):
    url = f"https://graph.microsoft.com/v1.0/users/{mailbox}/mailFolders('Inbox')/messages"
    headers = {'Authorization': f'Bearer {access_token}'}
    params = {
        '$top': limit,
        '$orderby': 'receivedDateTime desc',
        '$select': 'id,subject,from,receivedDateTime,bodyPreview,hasAttachments'
    }
    response = requests.get(url, headers=headers, params=params)
    return response.json().get('value', [])

# Move processed email to folder
def move_email_to_folder(access_token, mailbox, message_id, folder_id):
    url = f"https://graph.microsoft.com/v1.0/users/{mailbox}/messages/{message_id}/move"
    headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
    data = {'destinationId': folder_id}
    response = requests.post(url, headers=headers, json=data)
    return response.status_code == 201

Folder Management

# Create processed folder if it doesn't exist
def ensure_processed_folder(access_token, mailbox):
    # Check existing folders
    url = f"https://graph.microsoft.com/v1.0/users/{mailbox}/mailFolders"
    headers = {'Authorization': f'Bearer {access_token}'}
    response = requests.get(url, headers=headers)

    folders = response.json().get('value', [])
    for folder in folders:
        if folder['displayName'] == 'Processed':
            return folder['id']

    # Create folder if not found
    data = {'displayName': 'Processed'}
    response = requests.post(url, headers=headers, json=data)
    return response.json()['id'] if response.status_code == 201 else None

Integration Architecture

The email processing system integrates with external systems through modular business logic components.

graph LR
    subgraph EmailProc["Email Processing"]
        Email[Email Content]
        Parser[Content Parser]
        Validator[Data Validator]
    end

    subgraph ExtSys["External Systems"]
        DB[(Database)]
        API[External APIs]
        FileStorage[File Storage]
        Webhook[Webhook Notifications]
    end

    Email --> Parser
    Parser --> Validator
    Validator --> DB
    Validator --> API
    Validator --> FileStorage
    Validator --> Webhook

Business logic components operate independently of email retrieval, enabling the system to adapt to different processing requirements without modifying the Graph API integration.

Deployment and Monitoring

Production deployment requires scheduled execution and operational monitoring capabilities.

Scheduling Options

Linux/macOS (cron):

# Run every 15 minutes during business hours
*/15 9-17 * * 1-5 /usr/bin/python3 /path/to/email_scraper.py

Windows (Task Scheduler): Configure scheduled task with appropriate service account permissions and error handling policies.

Monitoring and Logging

The system should log processing metrics including: - Email processing counts and timing - Authentication token refresh status - API rate limiting and throttling responses - Business logic processing errors - Folder operation success/failure rates

Token management requires handling Azure AD token expiration (typically 1 hour for access tokens). The client credentials flow provides reliable token renewal without user interaction.

Security Considerations

Application credentials require secure storage and rotation policies. Client secrets should use Azure Key Vault or equivalent secure storage rather than configuration files.

Network access should restrict the processing application to necessary Graph API endpoints. The Exchange Online access policy provides mailbox-level restrictions, but network-level controls add additional security layers.

Audit logging should capture all email processing activities for compliance and troubleshooting purposes. The processed folder approach provides built-in audit trails, but separate logging systems enable more detailed operational analysis.

Future Development: Private AI Model Integration

The current implementation establishes the foundational infrastructure for AI-powered email processing using standard cloud AI services. Once operational, this system provides an ideal testing environment for evaluating private AI model performance against public alternatives.

Future development will explore replacing public AI models with private, controlled alternatives that operate under specific data handling agreements. Private models offer enhanced data security by ensuring email content remains within controlled infrastructure boundaries rather than being processed by third-party AI services.

The Meridian system presents an excellent candidate for A/B testing private versus public AI model performance. The implementation can process 50% of incoming emails using private AI models while processing the remaining 50% with public models, enabling direct accuracy and performance comparisons across identical email content.

This testing approach allows measurement of processing quality, response time, and operational reliability between model types. The results will inform decisions about expanding private AI model usage across other AIC Holdings automation systems.

The modular architecture established with Meridian's email processing enables straightforward AI model substitution without requiring changes to authentication, email retrieval, or folder management components. This design supports seamless migration to private models once testing validates their effectiveness for email content analysis tasks.