A full-stack AI-powered email management system that intelligently processes, classifies, and responds to Gmail emails using Groq LLM.
- 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
- 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
- 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
- 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
- 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
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
- Python 3.9+
- Node.js 18+
- Gmail account with App Password enabled
- Groq API key (free at https://console.groq.com/)
IMPORTANT: You MUST use a Gmail App Password, not your regular password.
- Go to your Google Account: https://myaccount.google.com/
- Click Security in the left sidebar
- Enable 2-Step Verification (required for App Passwords)
- Search for "App passwords" or go to: https://myaccount.google.com/apppasswords
- Select Mail and Other (Custom name)
- Enter name: "AI Email Agent"
- Click Generate
- Copy the 16-character password (e.g.,
abcd efgh ijkl mnop) - Remove spaces:
abcdefghijklmnop
# 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/LinuxEdit 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=Truepython -c "import secrets; print(secrets.token_hex(32))"- Go to https://console.groq.com/
- Sign up (free)
- Navigate to API Keys
- Create new key
- Copy to
.env
# Navigate to frontend directory
cd frontend
# Install dependencies
npm installcd backend
venv\Scripts\activate # Windows
# OR
source venv/bin/activate # Mac/Linux
python main.pyBackend runs at: http://localhost:8000 API docs at: http://localhost:8000/docs
cd frontend
npm run devFrontend runs at: http://localhost:5173
- Open http://localhost:5173
- Enter your Gmail address
- Enter the 16-character App Password (no spaces)
- Click Login
- Login: App Password sent to backend via HTTPS
- Session Creation: Password stored in Python dictionary (server memory)
- Token Issued: JWT token sent to frontend
- SessionStorage: Frontend stores token in sessionStorage (NOT localStorage)
- Page Refresh: Token persists, no re-login needed
- Browser Close: SessionStorage cleared automatically
- Server Restart: In-memory sessions cleared
- β Disk files
- β Cookies
- β localStorage
- β Database
- β Log files
- Closing browser/tab
- Server restart
- Explicit logout
- Session expiry (24 hours)
# 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}")# 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}")# 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']}")- β Using App Password, not regular password?
- β App Password has no spaces?
- β 2-Step Verification enabled?
- β Generated new App Password?
- β Port 993 not blocked by firewall?
- β IMAP_HOST=imap.gmail.com in .env?
- β Gmail IMAP enabled in settings?
- β Port 587 not blocked?
- β Using correct App Password?
- β "Less secure app access" not needed (App Password works)
- β Valid API key in .env?
- β API key has quota remaining?
- β Internet connection working?
- β Backend running on port 8000?
- β CORS configured correctly?
- β Valid JWT token?
- β Server restarted? (clears sessions)
- β Browser closed? (clears sessionStorage)
- β Token expired? (24 hours)
# Delete and recreate database
rm email_agent.db
python main.py # Recreates on startupPOST /auth/login- Login with Gmail credentialsPOST /auth/logout- Logout and clear sessionGET /auth/verify- Verify session validity
GET /emails/fetch- Fetch unread emails (no AI processing)POST /emails/process- Fetch + AI processingGET /emails/threads- Get emails grouped by threadsPOST /emails/send-reply- Send custom replyPOST /emails/auto-reply- Send AI-generated reply (requires confirmation)POST /emails/daily-report- Generate and send daily report
GET /contacts/scores- Get all contact scores
Full API documentation: http://localhost:8000/docs
- Never commit .env files to version control
- Use HTTPS in production (not HTTP)
- Rotate App Passwords periodically
- Monitor API usage (Groq quotas)
- Set strong SECRET_KEY (32+ characters)
- Enable 2FA on Gmail account
- Review processed emails before auto-reply
- Backup database periodically
- Create account on hosting platform
- Connect GitHub repository
- Set environment variables:
SECRET_KEYGROQ_API_KEYIMAP_HOST,IMAP_PORTSMTP_HOST,SMTP_PORT
- Deploy from
backend/directory - Command:
uvicorn main:app --host 0.0.0.0 --port 8000
- Create account on hosting platform
- Connect GitHub repository
- Set build settings:
- Build command:
npm run build - Output directory:
dist - Root directory:
frontend
- Build command:
- Set environment variables:
VITE_API_URL=https://your-backend.com
- Deploy
- 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
| 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 |
- Login with Gmail + App Password
- Process Emails - Click "Process New Emails"
- Review - Hover over emails to see details
- Filter - Use category tabs to filter
- Auto Reply - Click "AI Auto Reply" β Confirm
- Daily Report - Click "Send Daily Report"
- Logout - Clears session
- Fork repository
- Create feature branch
- Commit changes
- Push to branch
- Create Pull Request
MIT License - See LICENSE file
- Groq: LLM API
- FastAPI: Backend framework
- React: Frontend framework
- TailwindCSS: Styling
For issues and questions:
- Open GitHub issue
- Check troubleshooting section
- Review API docs at
/docs
Built with β€οΈ for intelligent email management