Skip to content

RKG765/AI-Email-Agent

Repository files navigation

AI Email Agent πŸ€–πŸ“§

A full-stack AI-powered email management system that intelligently processes, classifies, and responds to Gmail emails using Groq LLM.

🌟 Features

Core Functionality

  • Gmail Integration: Connect via IMAP/SMTP using Gmail App Password
  • AI Classification: Automatically categorize emails as important/less important/not important
  • Priority Scoring: 0-100 score based on content + contact history
  • Contact-Based Ranking: Track frequent senders, starred contacts, and recent interactions
  • Thread Reconstruction: Group related emails and generate thread summaries
  • Email Summarization: 2-3 line AI-generated summaries
  • Event Extraction: Detect deadlines, meetings, and important dates
  • AI Reply Generation: Professional reply drafts for each email
  • One-Click Auto Reply: Send AI-generated replies with confirmation
  • Daily Reports: Consolidated email summary sent to your inbox

Security & Session Management

  • Session-Only Password Storage: Gmail App Password stored ONLY in server memory
  • No Disk Persistence: Credentials never saved to disk, cookies, or localStorage
  • Refresh-Safe: Page refresh doesn't require re-login
  • Browser Restart Clears Session: Closing browser requires new login
  • JWT Authentication: Secure token-based API access

UI Features

  • Color-Coded Indicators:
    • πŸ”΄ Red Dot = Important
    • 🟒 Green Dot = Less Important
    • 🟀 Brown Dot = Not Important
  • Hover Detail Panels: View full email info on hover
  • Filter by Category: Quick filtering by importance level
  • Responsive Design: Tailwind CSS for modern UI

πŸ› οΈ Tech Stack

Backend

  • FastAPI: Modern Python web framework
  • Groq API: LLM for classification, summarization, and reply generation
  • IMAP/SMTP: Direct Gmail integration
  • SQLite: Contact scores and processed email tracking
  • JWT: Secure authentication
  • In-Memory Sessions: Secure password management

Frontend

  • React 18: Modern React with hooks
  • TypeScript: Type-safe development
  • Vite: Fast build tool
  • TailwindCSS: Utility-first CSS
  • React Router: Client-side routing
  • Axios: HTTP client

πŸ“ Project Structure

mail_ai_bot/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.py          # Authentication endpoints
β”‚   β”‚   β”‚   β”œβ”€β”€ emails.py        # Email processing endpoints
β”‚   β”‚   β”‚   └── contacts.py      # Contact scores endpoint
β”‚   β”‚   β”œβ”€β”€ core/
β”‚   β”‚   β”‚   β”œβ”€β”€ config.py        # Configuration settings
β”‚   β”‚   β”‚   β”œβ”€β”€ database.py      # SQLite database layer
β”‚   β”‚   β”‚   β”œβ”€β”€ session.py       # In-memory session storage
β”‚   β”‚   β”‚   └── auth.py          # JWT authentication
β”‚   β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”‚   └── schemas.py       # Pydantic models
β”‚   β”‚   └── services/
β”‚   β”‚       β”œβ”€β”€ imap_service.py  # Email fetching
β”‚   β”‚       β”œβ”€β”€ smtp_service.py  # Email sending
β”‚   β”‚       β”œβ”€β”€ llm_service.py   # Groq LLM integration
β”‚   β”‚       └── thread_service.py # Thread reconstruction
β”‚   β”œβ”€β”€ main.py                  # FastAPI application
β”‚   β”œβ”€β”€ requirements.txt         # Python dependencies
β”‚   └── .env.example             # Environment template
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ EmailCard.tsx    # Email card with color dot
β”‚   β”‚   β”‚   β”œβ”€β”€ HoverDetailPanel.tsx # Detailed email info
β”‚   β”‚   β”‚   └── ConfirmModal.tsx # Confirmation dialog
β”‚   β”‚   β”œβ”€β”€ pages/
β”‚   β”‚   β”‚   β”œβ”€β”€ Login.tsx        # Login page
β”‚   β”‚   β”‚   └── Dashboard.tsx    # Main dashboard
β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   └── api.ts           # API service layer
β”‚   β”‚   β”œβ”€β”€ types/
β”‚   β”‚   β”‚   └── email.ts         # TypeScript types
β”‚   β”‚   β”œβ”€β”€ App.tsx              # Main app component
β”‚   β”‚   β”œβ”€β”€ main.tsx             # Entry point
β”‚   β”‚   └── index.css            # Global styles
β”‚   β”œβ”€β”€ package.json             # Frontend dependencies
β”‚   β”œβ”€β”€ vite.config.ts           # Vite configuration
β”‚   β”œβ”€β”€ tailwind.config.js       # Tailwind configuration
β”‚   └── tsconfig.json            # TypeScript configuration
└── README.md                    # This file

πŸš€ Setup Instructions

Prerequisites

1. Create Gmail App Password

IMPORTANT: You MUST use a Gmail App Password, not your regular password.

Steps:

  1. Go to your Google Account: https://myaccount.google.com/
  2. Click Security in the left sidebar
  3. Enable 2-Step Verification (required for App Passwords)
  4. Search for "App passwords" or go to: https://myaccount.google.com/apppasswords
  5. Select Mail and Other (Custom name)
  6. Enter name: "AI Email Agent"
  7. Click Generate
  8. Copy the 16-character password (e.g., abcd efgh ijkl mnop)
  9. Remove spaces: abcdefghijklmnop

⚠️ Save this password securely - you'll need it to login to the app.

2. Backend Setup

# Navigate to backend directory
cd backend

# Create virtual environment
python -m venv venv

# Activate virtual environment
# Windows:
venv\Scripts\activate
# Mac/Linux:
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Create .env file
copy .env.example .env  # Windows
# OR
cp .env.example .env    # Mac/Linux

3. Configure Environment Variables

Edit backend/.env:

# Generate secret key with: python -c "import secrets; print(secrets.token_hex(32))"
SECRET_KEY=your-secret-key-here-replace-with-random-string

# Get from https://console.groq.com/
GROQ_API_KEY=gsk_your_groq_api_key_here

# IMAP/SMTP Configuration (Gmail - don't change)
IMAP_HOST=imap.gmail.com
IMAP_PORT=993
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587

# Application Settings
ENVIRONMENT=development
DEBUG=True

Generate Secret Key:

python -c "import secrets; print(secrets.token_hex(32))"

Get Groq API Key:

  1. Go to https://console.groq.com/
  2. Sign up (free)
  3. Navigate to API Keys
  4. Create new key
  5. Copy to .env

4. Frontend Setup

# Navigate to frontend directory
cd frontend

# Install dependencies
npm install

5. Running the Application

Start Backend (Terminal 1):

cd backend
venv\Scripts\activate  # Windows
# OR
source venv/bin/activate  # Mac/Linux

python main.py

Backend runs at: http://localhost:8000 API docs at: http://localhost:8000/docs

Start Frontend (Terminal 2):

cd frontend
npm run dev

Frontend runs at: http://localhost:5173

6. Login

  1. Open http://localhost:5173
  2. Enter your Gmail address
  3. Enter the 16-character App Password (no spaces)
  4. Click Login

πŸ” Session-Only Password Storage Explained

How It Works:

  1. Login: App Password sent to backend via HTTPS
  2. Session Creation: Password stored in Python dictionary (server memory)
  3. Token Issued: JWT token sent to frontend
  4. SessionStorage: Frontend stores token in sessionStorage (NOT localStorage)
  5. Page Refresh: Token persists, no re-login needed
  6. Browser Close: SessionStorage cleared automatically
  7. Server Restart: In-memory sessions cleared

What's NOT Stored:

  • ❌ Disk files
  • ❌ Cookies
  • ❌ localStorage
  • ❌ Database
  • ❌ Log files

What Clears Session:

  • Closing browser/tab
  • Server restart
  • Explicit logout
  • Session expiry (24 hours)

πŸ§ͺ Testing

Test IMAP Connection

# backend/test_imap.py
from app.services.imap_service import IMAPService

imap = IMAPService(
    email_address="your.email@gmail.com",
    app_password="your-app-password-here",
    host="imap.gmail.com",
    port=993
)

try:
    imap.connect()
    print("βœ… IMAP Connection Successful")
    emails = imap.fetch_unread_emails(limit=5)
    print(f"πŸ“§ Found {len(emails)} unread emails")
    imap.disconnect()
except Exception as e:
    print(f"❌ IMAP Error: {e}")

Test SMTP Sending

# backend/test_smtp.py
from app.services.smtp_service import SMTPService

smtp = SMTPService(
    email_address="your.email@gmail.com",
    app_password="your-app-password-here",
    host="smtp.gmail.com",
    port=587
)

try:
    smtp.send_email(
        to_email="your.email@gmail.com",
        subject="Test Email",
        body="This is a test from AI Email Agent"
    )
    print("βœ… SMTP Send Successful")
except Exception as e:
    print(f"❌ SMTP Error: {e}")

Test Groq Integration

# backend/test_groq.py
from app.services.llm_service import LLMService
from app.core.config import settings

llm = LLMService(api_key=settings.GROQ_API_KEY)

# Test classification
result = llm.classify_email(
    subject="Meeting Tomorrow",
    body="Can we meet tomorrow at 2pm to discuss the project?",
    sender="boss@company.com",
    contact_score=50
)

print(f"Classification: {result['classification']}")
print(f"Priority Score: {result['priority_score']}")
print(f"Reasoning: {result['reasoning']}")

πŸ› Troubleshooting

Backend Issues

"Authentication failed"

  • βœ… Using App Password, not regular password?
  • βœ… App Password has no spaces?
  • βœ… 2-Step Verification enabled?
  • βœ… Generated new App Password?

"IMAP connection failed"

  • βœ… Port 993 not blocked by firewall?
  • βœ… IMAP_HOST=imap.gmail.com in .env?
  • βœ… Gmail IMAP enabled in settings?

"SMTP send failed"

  • βœ… Port 587 not blocked?
  • βœ… Using correct App Password?
  • βœ… "Less secure app access" not needed (App Password works)

"Groq API error"

  • βœ… Valid API key in .env?
  • βœ… API key has quota remaining?
  • βœ… Internet connection working?

Frontend Issues

"Failed to fetch emails"

  • βœ… Backend running on port 8000?
  • βœ… CORS configured correctly?
  • βœ… Valid JWT token?

"Session expired"

  • βœ… Server restarted? (clears sessions)
  • βœ… Browser closed? (clears sessionStorage)
  • βœ… Token expired? (24 hours)

Database Issues

"Database locked"

# Delete and recreate database
rm email_agent.db
python main.py  # Recreates on startup

πŸ“Š API Endpoints

Authentication

  • POST /auth/login - Login with Gmail credentials
  • POST /auth/logout - Logout and clear session
  • GET /auth/verify - Verify session validity

Emails

  • GET /emails/fetch - Fetch unread emails (no AI processing)
  • POST /emails/process - Fetch + AI processing
  • GET /emails/threads - Get emails grouped by threads
  • POST /emails/send-reply - Send custom reply
  • POST /emails/auto-reply - Send AI-generated reply (requires confirmation)
  • POST /emails/daily-report - Generate and send daily report

Contacts

  • GET /contacts/scores - Get all contact scores

Full API documentation: http://localhost:8000/docs

πŸ”’ Security Notes

  1. Never commit .env files to version control
  2. Use HTTPS in production (not HTTP)
  3. Rotate App Passwords periodically
  4. Monitor API usage (Groq quotas)
  5. Set strong SECRET_KEY (32+ characters)
  6. Enable 2FA on Gmail account
  7. Review processed emails before auto-reply
  8. Backup database periodically

🚒 Deployment

Backend (Railway/Render/Fly.io)

  1. Create account on hosting platform
  2. Connect GitHub repository
  3. Set environment variables:
    • SECRET_KEY
    • GROQ_API_KEY
    • IMAP_HOST, IMAP_PORT
    • SMTP_HOST, SMTP_PORT
  4. Deploy from backend/ directory
  5. Command: uvicorn main:app --host 0.0.0.0 --port 8000

Frontend (Vercel/Netlify)

  1. Create account on hosting platform
  2. Connect GitHub repository
  3. Set build settings:
    • Build command: npm run build
    • Output directory: dist
    • Root directory: frontend
  4. Set environment variables:
    • VITE_API_URL=https://your-backend.com
  5. Deploy

Production Considerations

  • Use PostgreSQL instead of SQLite
  • Implement rate limiting
  • Add request logging
  • Use Redis for session storage
  • Enable HTTPS/SSL
  • Set up monitoring (Sentry)
  • Configure auto-scaling
  • Regular backups

πŸ“ Environment Variables Reference

Backend (.env)

Variable Description Example
SECRET_KEY JWT signing key abc123...
GROQ_API_KEY Groq API key gsk_...
IMAP_HOST IMAP server imap.gmail.com
IMAP_PORT IMAP port 993
SMTP_HOST SMTP server smtp.gmail.com
SMTP_PORT SMTP port 587
ENVIRONMENT Environment development
DEBUG Debug mode True

🎯 Usage Flow

  1. Login with Gmail + App Password
  2. Process Emails - Click "Process New Emails"
  3. Review - Hover over emails to see details
  4. Filter - Use category tabs to filter
  5. Auto Reply - Click "AI Auto Reply" β†’ Confirm
  6. Daily Report - Click "Send Daily Report"
  7. Logout - Clears session

🀝 Contributing

  1. Fork repository
  2. Create feature branch
  3. Commit changes
  4. Push to branch
  5. Create Pull Request

πŸ“„ License

MIT License - See LICENSE file

πŸ™ Credits

  • Groq: LLM API
  • FastAPI: Backend framework
  • React: Frontend framework
  • TailwindCSS: Styling

πŸ“§ Support

For issues and questions:

  • Open GitHub issue
  • Check troubleshooting section
  • Review API docs at /docs

Built with ❀️ for intelligent email management

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published