Build an AI-Powered Email Manager with OAuth

Create a production-ready email management application with OAuth authentication, AI-powered analysis, and multi-provider support. Learn advanced integration patterns while building something truly useful.

⏱️ 45-60 minutes 📚 Advanced 📧 OAuth + AI

🚀 What You'll Build

A complete email management application that:

  • Multi-Provider OAuth: Connect Gmail, Outlook, and Yahoo Mail securely
  • AI-Powered Analysis: Intelligent email summaries, sentiment analysis, and priority detection
  • Smart Organization: Automatic labeling and categorization with AI recommendations
  • Custom Templates: Create your own AI prompt templates for email processing
  • Real-time Interface: Modern web app with live updates and responsive design
  • Analytics Dashboard: Insights into your email patterns and AI analysis results

Final Result: A production-ready email manager that showcases advanced Fiberwise capabilities including OAuth, AI agents, data models, and modern UI patterns.

📚 What You'll Learn

OAuth & Authentication Mastery

  • OAuth 2.0 Implementation: Complete flow from provider setup to token management
  • Multi-Provider Support: Handle different OAuth providers (Google, Microsoft, Yahoo)
  • Secure Credential Management: Best practices for storing and using API credentials
  • Error Handling: Robust authentication error recovery and user experience

Advanced App Development

  • Agent Integration: Build custom agents for email processing and AI analysis
  • Data Models: Design complex data schemas for email analytics and templates
  • Modern UI Components: Create reusable web components with real-time updates
  • Production Architecture: Scalable patterns for enterprise-ready applications

📋 Prerequisites: Your Setup Checklist

Before you begin, you need a fully configured Fiberwise environment. This is the foundation for building any app on the platform.

🔧 Required Setup

✅ All Set?

Once all boxes are checked, you are ready to proceed. If not, please complete the linked guides first.

🛠️ Step 1: Get the Email App Code

The email agent app is located in the fiber-apps repository. Let's navigate to it and explore the structure.

1
Navigate to Email Agent App
cd fiber-apps/email-agent-app
2
Explore the App Structure
ls -la
# You'll see:
# app_manifest.yaml  - App configuration and data models
# index.js           - App entry point and initialization
# src/               - Frontend components and services
# agents/            - AI agents for email analysis
# functions/         - Email fetching and processing functions

📁 App Architecture

📁 email-agent-app/
📄 app_manifest.yaml - App config, models, OAuth settings
📄 index.js - Frontend initialization
📁 src/
📁 components/ - UI components
📁 services/ - Email services
📁 agents/
📄 email_agent.py - AI email analysis
📁 functions/
📄 get_recent_emails.py - Fetch emails from Gmail
📄 get_email.py - Get individual email details

📋 App Manifest Deep Dive

# app_manifest.yaml - The heart of your Fiberwise app
app:
  name: Email Agent App
  app_slug: email-agent-app-2
  version: 1.0.126
  description: AI-powered email management with Gmail integration

models:
  - name: Cached Messages
    model_slug: cached_messages
    fields:
      - name: Connection ID
        field_column: connection_id
        type: string
        is_required: true
      - name: Message ID
        field_column: message_id
        type: string
        is_required: true
      - name: Subject
        field_column: subject
        type: string
      - name: Sender
        field_column: sender
        type: string
      - name: Body Preview
        field_column: body_preview
        type: text
      - name: Message Date
        field_column: message_date
        type: string
      - name: Labels
        field_column: labels
        type: json

  - name: Email Analyses
    model_slug: email_analyses
    fields:
      - name: Message ID
        field_column: message_id
        type: string
        is_required: true
      - name: Sentiment
        field_column: sentiment
        type: string
      - name: Priority
        field_column: priority
        type: string
      - name: Summary
        field_column: summary
        type: text
      - name: Topics
        field_column: topics
        type: json
      - name: Action Items
        field_column: action_items
        type: json

oauth_configs:
  - provider: gmail
    oauth_provider_slug: fiberwise-developer
    scopes:
      - https://www.googleapis.com/auth/gmail.readonly
      - https://www.googleapis.com/auth/gmail.send
      - https://www.googleapis.com/auth/userinfo.profile
    configuration:
      client_id: your-gmail-client-id
      client_secret: your-gmail-client-secret

agents:
  - name: email-analyzer
    implementation_path: agents/email_analyzer.py
    permissions:
      - llm.completion
      - data.write
      - oauth.gmail

functions:
  - name: get_recent_emails
    implementation_path: functions/get_recent_emails.py
    description: Fetches recent emails from Gmail
    permissions:
      - oauth.gmail
      - data.write

navigation:
  - component: email-app
    icon: fas fa-inbox
    path: /
    title: Inbox
  - component: email-settings
    icon: fas fa-cog
    path: /settings
    title: Settings

🎯 Key Architecture Insights

  • OAuth Integration: Complete Gmail OAuth setup with proper scopes
  • Data Models: Separate models for email cache and AI analysis results
  • Agent Permissions: Granular permissions for LLM access and data operations
  • Function-Based Architecture: Serverless functions for email fetching and processing

🔐 Step 2: Configure OAuth for Gmail

To access Gmail, we need to set up OAuth credentials. This allows users to securely connect their Gmail accounts.

🔐 OAuth Flow Overview

👤
User clicks "Connect Gmail"
🔐
Redirect to Google OAuth
User grants permissions
📧
App can access emails
1
Create Google Cloud Project

Go to Google Cloud Console and create a new project.

# Project Name: "My Email Agent App"
# Project ID: Will be auto-generated (e.g., my-email-agent-app-123456)
2
Enable Gmail API

In your Google Cloud project, enable the Gmail API:

  1. Navigate to "APIs & Services" → "Library"
  2. Search for "Gmail API"
  3. Click "Enable"
3
Create OAuth Credentials

Set up OAuth 2.0 credentials for web application:

Application Type: Web application
Name: Email Agent App
Authorized redirect URIs: http://localhost:5757/api/v1/oauth/callback/fiberwise-developer
4
Download OAuth Configuration

Download the OAuth JSON credentials from Google Cloud Console:

  1. Go to "APIs & Services" → "Credentials"
  2. Find your OAuth 2.0 Client ID
  3. Click the download icon to get the JSON file
  4. Save it as oauth-credentials.json in your project directory
5
Import OAuth Configuration with CLI

Use the Fiberwise CLI to automatically import and configure OAuth:

# Import OAuth configuration automatically
fiber app oauth import oauth-credentials.json

# Verify import was successful
fiber app oauth list

✅ The CLI automatically detects the Google OAuth format and converts it to Fiberwise configuration

🎯 Benefits of OAuth Import CLI

  • Automatic Detection: Recognizes Google, GitHub, Microsoft, and other provider formats
  • Format Conversion: Converts to Fiberwise-compatible configuration automatically
  • Error Prevention: Validates configuration before importing
  • Dry Run Support: Preview changes with --dry-run flag
  • Choose "External" user type
  • Fill in app name: "My Email Manager"
  • Add your email as developer contact
  • 3. Create OAuth Credentials

    1. Go to APIs & Services → Credentials
    2. Click "Create Credentials" → "OAuth 2.0 Client IDs"
    3. Application type: "Web application"
    4. Add redirect URI: http://localhost:7001/api/v1/credentials/auth/callback/google

    Configure OAuth in Fiberwise

    Now let's connect your Google credentials to Fiberwise:

    # Configure Google OAuth provider
    fiber account oauth configure google \
      --client-id "YOUR_GOOGLE_CLIENT_ID" \
      --client-secret "YOUR_GOOGLE_CLIENT_SECRET" \
      --redirect-uri "http://localhost:7001/api/v1/credentials/auth/callback/google" \
      --scopes "https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.send"
    
    # Verify the configuration
    fiber account oauth list-providers

    ✅ Expected Output

    Configured OAuth Providers:
    --------------------------------------------------
    Provider ID: google
    Client ID: 123456-abc.apps.googleusercontent.com
    Scopes: gmail.readonly, gmail.send
    Status: Configured ✓

    📊 Step 3: Understand the Data Models

    The email app uses three main data models to store and organize email data efficiently.

    📧 cached_messages

    Stores email metadata for fast loading and offline access

    🆔 connection_id - OAuth connection identifier
    ✉️ message_id - Unique email message ID
    📝 subject - Email subject line
    👤 sender - Email sender address
    📅 message_date - When email was sent
    🏷️ labels - Email labels (INBOX, SENT, etc.)

    🧠 email_analyses

    AI-generated insights and analysis for each email

    📧 message_id - Links to cached_messages
    😊 sentiment - positive/negative/neutral
    ⚡ priority - high/medium/low
    📋 summary - AI-generated summary
    🏷️ topics - Extracted topics array
    ✅ action_items - Detected action items

    📝 email_prompt_templates

    Customizable prompt templates for AI analysis

    📛 template_name - Template identifier
    📄 template_content - Prompt template with placeholders
    📝 description - What the template is for
    👤 user_id - User who owns this template

    🚀 Step 4: Install and Run the App

    Now let's install the email app and see it in action.

    1
    Install the App
    fiber app install email-agent-app

    ✅ This installs the app, creates database tables, and registers all components.

    2
    Start the Development Server
    fiber start --dev

    ✅ Your email app is now running at http://localhost:5757

    3
    Access the Email App

    Navigate to the email app in your browser:

    # Open in browser:
    http://localhost:5757/apps/email-agent-app-2

    🔗 Step 5: Connect Your Gmail Account

    Let's connect your Gmail account and start managing emails with AI.

    1
    Navigate to Email Connections

    In the email app, go to Settings → Email Connections

    2
    Add Gmail Connection

    Click "Add Connection" and select "Gmail (OAuth)"

    3
    Authorize Access

    Complete the OAuth flow by granting permissions to:

    • Read your email messages
    • Send emails on your behalf
    • Access basic profile information
    4
    Load Recent Emails

    Once connected, click "Load Recent Emails" to fetch your latest messages

    ✅ Your emails will be cached locally for fast access and AI analysis

    🤖 Step 6: AI Email Analysis

    Watch as AI analyzes your emails for sentiment, priority, and key topics.

    🤖 What the AI Analyzes

    😊
    Sentiment Analysis

    Detects if emails are positive, negative, or neutral in tone

    Priority Detection

    Identifies urgent emails that need immediate attention

    🏷️
    Topic Extraction

    Automatically tags emails with relevant topics and categories

    Action Items

    Finds tasks and action items mentioned in your emails

    1
    Analyze an Email

    Click on any email in your inbox to view AI analysis

    // The AI agent automatically analyzes:
    {
      "sentiment": "positive",
      "priority": "high", 
      "topics": ["meeting", "project", "deadline"],
      "action_items": ["Schedule follow-up call", "Review documents"],
      "summary": "Meeting request for project discussion..."
    }

    ⚡ Critical FIBER.data API Understanding

    🚨 Critical Issue: Data Structure in FIBER.data API

    Problem: The most common issue when building email apps is accessing data incorrectly from the FIBER.data API. This causes FIBER.data.listItems() to appear to return 0 results when data actually exists.

    Understanding API Response Structure

    The FIBER.data API returns items with nested data structure:

    {
      "items": [
        {
          "item_id": "uuid-123",
          "app_id": "your-app-id", 
          "model_id": "model-uuid",
          "created_at": "2024-01-01T10:00:00Z",
          "updated_at": "2024-01-01T10:00:00Z",
          "data": {
            "subject": "Your actual email subject",
            "sender": "[email protected]",
            "connection_id": "gmail-connection-123",
            "labels": ["INBOX", "IMPORTANT"]
          }
        }
      ],
      "total": 10,
      "page": 1,
      "pages": 1
    }

    ❌ Common Mistake (Returns Undefined)

    // This is WRONG - accessing fields directly on item
    const result = await FIBER.data.listItems('cached_messages');
    result.items.filter(item => 
      item.subject && // undefined!
      item.connection_id === connectionId // undefined!
    );

    ✅ Correct Implementation

    // This is CORRECT - accessing fields via item.data
    const result = await FIBER.data.listItems('cached_messages');
    result.items.filter(item => 
      item.data.subject && // ✅ Works!
      item.data.connection_id === connectionId // ✅ Works!
    );

    Real Email App Example

    Here's the actual working code from the email search component:

    // src/components/email-search.js
    async loadCachedMessages(limit) {
      try {
        // Load cached messages using FIBER.data.listItems
        const result = await FIBER.data.listItems('cached_messages', {
          limit: limit * 2 // Get more to account for filtering
          // Note: sort parameter not supported by API
        });
        
        if (result && result.items) {
          // Filter by connection and label client-side
          const filteredMessages = result.items
            .filter(msg => 
              msg.data.connection_id === this.connectionId && 
              msg.data.labels && msg.data.labels.includes(this.searchLabel)
            )
            .map(msg => ({
              id: msg.data.message_id,
              subject: msg.data.subject,
              sender: msg.data.sender,
              from: msg.data.sender,
              date: msg.data.message_date,
              snippet: msg.data.body_preview
            }))
            .sort((a, b) => {
              // Sort by message date, newest first
              const dateA = new Date(a.date);
              const dateB = new Date(b.date);
              return dateB - dateA;
            })
            .slice(0, limit); // Limit to requested amount after sorting
    
          console.log(`Loaded ${filteredMessages.length} cached messages`);
          return filteredMessages;
        }
        
        return [];
      } catch (error) {
        console.error('Error loading cached messages:', error);
        return [];
      }
    }

    🎯 Key Insights

    API Limitations & Workarounds

    ❌ Not Supported

    • Server-side sorting
    • Complex filtering
    • Full-text search
    • Aggregation functions

    ✅ Workarounds

    • Client-side sorting with JavaScript
    • Fetch more data and filter locally
    • Use simple filters in listItems()
    • Implement pagination for large datasets

    🚀 Step 3: Deploy and Test the App

    Install the App

    # Make sure Fiberwise server is running
    fiber start --dev
    
    # Install the email agent app
    fiber app install email-agent-app
    
    # Verify installation
    fiber app list

    Access the Email App

    Open your browser and navigate to the email app:

    # Open in browser:
    http://localhost:5757/apps/email-agent-app-2

    Connect Your Gmail Account

    Now the fun part - let's connect your Gmail account:

    1. In the email app, go to Settings → Email Connections
    2. Click "Add Connection" and select "Gmail (OAuth)"
    3. Complete the OAuth flow by granting permissions to:
      • Read your email messages
      • Send emails on your behalf
      • Access basic profile information
    4. Once connected, click "Load Recent Emails" to fetch your latest messages

    🎬 What Happens During OAuth Flow

    1. Initiate: App redirects to Google's OAuth server
    2. Authorize: You grant permissions to access Gmail
    3. Callback: Google redirects back with authorization code
    4. Exchange: App exchanges code for access token
    5. Store: Token is securely stored in Fiberwise credentials

    Test Email Fetching

    Once connected, test that everything works:

    # Test fetching emails via CLI
    fiber activate email-agent --input-data '{
      "action": "fetch_emails",
      "provider": "google",
      "limit": 5
    }'

    🔧 Common Issues & Solutions

    🧠 Step 4: Explore AI-Powered Email Features

    Email Analysis with AI

    The real power of this app comes from AI analysis. Let's see it in action:

    📧 Try These AI Features

    1. Smart Summaries: Click "Analyze" on any email to get an AI-generated summary
    2. Sentiment Detection: See if emails are positive, negative, or neutral
    3. Priority Assessment: AI determines if emails need urgent attention
    4. Topic Extraction: Identify key themes and subjects automatically

    Understanding the Email Agent

    Let's look at how the AI agent processes emails:

    # agents/email_agent.py - The brain of our email processing
    class EmailAgent:
        def analyze_email(self, email_content, template_name="default"):
            """
            Analyze email content using AI with customizable prompts
            """
            # Get the user's custom template or use default
            template = self.get_template(template_name)
            
            # Use Fiberwise LLM integration for analysis
            analysis = self.llm.complete(
                prompt=template.format(email_content=email_content),
                model="gpt-4",
                temperature=0.3
            )
            
            # Store results in our data model
            fiber.data.create_item('email_analyses', {
                'analysis_id': str(uuid.uuid4()),
                'summary': analysis.get('summary'),
                'sentiment': analysis.get('sentiment'),
                'priority': analysis.get('priority'),
                'topics': analysis.get('topics', []),
                'action_items': analysis.get('action_items', [])
            })
            
            return analysis

    Custom AI Templates

    One of the coolest features is creating your own AI prompt templates:

    📝 Create a Custom Template

    1. Go to the "Prompt Templates" section
    2. Click "New Template"
    3. Try this customer service template:
    Template Name: Customer Service Analysis
    
    Template Content:
    Analyze this customer email for support purposes:
    
    Email: {email_content}
    
    Please provide:
    1. Customer sentiment (happy/frustrated/neutral)
    2. Issue severity (low/medium/high/critical)
    3. Department to route to (billing/technical/sales)
    4. Urgency level (immediate/same-day/next-business-day)
    5. Suggested response tone (empathetic/professional/apologetic)
    
    Format as JSON.

    📊 Step 5: Analytics and Advanced Features

    Email Analytics Dashboard

    The app includes a powerful analytics dashboard that shows:

    Multi-Provider Support

    Want to add more email accounts? The app supports multiple providers:

    # Add Microsoft Outlook
    fiber account oauth configure microsoft \
      --client-id "YOUR_MICROSOFT_CLIENT_ID" \
      --client-secret "YOUR_MICROSOFT_CLIENT_SECRET" \
      --redirect-uri "http://localhost:7001/api/v1/credentials/auth/callback/microsoft" \
      --scopes "Mail.Read User.Read"
    
    # Add Yahoo Mail
    fiber account oauth configure yahoo \
      --client-id "YOUR_YAHOO_CLIENT_ID" \
      --client-secret "YOUR_YAHOO_CLIENT_SECRET" \
      --redirect-uri "http://localhost:7001/api/v1/credentials/auth/callback/yahoo" \
      --scopes "mail-r profile"

    Advanced Customization

    🎨 Ideas for Further Development

    🤖 Smart Auto-Reply

    Create an agent that generates contextual email responses based on your writing style and the email content.

    📅 Calendar Integration

    Extract meeting requests and automatically create calendar events with AI-suggested details.

    🔍 Advanced Search

    Implement semantic search that understands meaning, not just keywords, using AI embeddings.

    📈 Productivity Insights

    Track email response times, identify communication patterns, and suggest optimization opportunities.

    🎯 Step 6: Understanding the Technical Architecture

    OAuth Token Management

    Let's understand how the app handles OAuth security:

    // services/email-service.js - Secure token handling
    class EmailService {
        async getAuthenticatedClient(providerId) {
            // Fiberwise handles token refresh automatically
            const credentials = await FIBER.credentials.get(providerId);
            
            if (credentials.isExpired()) {
                // Automatic refresh - no user intervention needed
                await credentials.refresh();
            }
            
            return this.createProviderClient(credentials);
        }
        
        async fetchEmails(providerId, options = {}) {
            try {
                const client = await this.getAuthenticatedClient(providerId);
                return await client.listMessages(options);
            } catch (error) {
                if (error.status === 401) {
                    // Handle auth errors gracefully
                    throw new AuthenticationError('Please re-authorize your account');
                }
                throw error;
            }
        }
    }

    Data Flow Architecture

    📊 How Data Moves Through the App

    1. OAuth Setup: User authorizes → Credentials stored securely
    2. Email Fetching: UI requests → Service layer → Provider API → Fiberwise data store
    3. AI Analysis: Email content → Agent processing → LLM analysis → Results storage
    4. UI Updates: Real-time data binding → Component updates → User sees results

    Security Best Practices

    🔒 Security Features You Get

    🏆 Congratulations!

    You've successfully built and deployed a production-ready email management application! You now understand:

    🔐 OAuth Mastery

    • Complete OAuth 2.0 implementation
    • Multi-provider authentication
    • Secure token management
    • Error handling and recovery

    🤖 AI Integration

    • Custom agent development
    • LLM prompt engineering
    • Data model design
    • Template customization

    🏗️ App Architecture

    • Modern web components
    • Service layer patterns
    • Real-time data flow
    • Production deployment

    📊 Advanced Features

    • Analytics and insights
    • Custom templates
    • Multi-provider support
    • Extensible architecture

    🎯 Key Architecture Insights

    This tutorial demonstrated enterprise-grade Fiberwise patterns:

    🚀 What's Next?

    🔧 Extend the App

    Add calendar integration, smart auto-replies, or advanced search features

    Advanced Patterns

    🏢 Deploy to Production

    Learn about scaling, monitoring, and enterprise deployment

    Production Guide

    🌐 Explore OAuth Further

    Dive deeper into OAuth configurations and advanced provider setups

    OAuth Deep Dive

    🤖 Advanced AI Agents

    Build sophisticated multi-agent systems and workflow automation

    Agent Mastery

    🎉 You're Now an OAuth + AI Integration Expert!

    You've mastered one of the most complex aspects of modern app development: secure OAuth integration combined with intelligent AI processing. The email manager you built showcases enterprise-grade patterns that you can apply to any integration challenge.