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
✅ 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
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:
// 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
Data Access: Always use item.data.fieldName, never item.fieldName
Client-Side Filtering: API has limited filtering - fetch more and filter in JavaScript
Client-Side Sorting: API doesn't support sort parameters - sort after fetching
Error Handling: Always wrap FIBER.data calls in try-catch blocks
Performance: Use limit parameter to avoid fetching too much data
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:
In the email app, go to Settings → Email Connections
Click "Add Connection" and select "Gmail (OAuth)"
Complete the OAuth flow by granting permissions to:
Read your email messages
Send emails on your behalf
Access basic profile information
Once connected, click "Load Recent Emails" to fetch your latest messages
🎬 What Happens During OAuth Flow
Initiate: App redirects to Google's OAuth server
Authorize: You grant permissions to access Gmail
Callback: Google redirects back with authorization code
Exchange: App exchanges code for access token
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
Redirect URI mismatch: Ensure your Google Console redirect URI exactly matches the one in the fiber command
Scope errors: Make sure you've enabled Gmail API in Google Cloud Console
Token expired: The app handles refresh automatically, but you can manually re-authorize if needed
🧠 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
Smart Summaries: Click "Analyze" on any email to get an AI-generated summary
Sentiment Detection: See if emails are positive, negative, or neutral
Priority Assessment: AI determines if emails need urgent attention
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
Go to the "Prompt Templates" section
Click "New Template"
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:
Email Volume Trends: Track your email patterns over time
Sentiment Analysis: See the emotional tone of your inbox
Priority Distribution: Understand what emails need attention
Topic Clustering: Visualize what subjects you receive most
Multi-Provider Support
Want to add more email accounts? The app supports multiple providers:
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.
🤝 Share Your Success
Show off what you built and get ideas from the community: