An intelligent email automation system that leverages AI to read, analyze, and intelligently respond to incoming Gmail messages. Built with FastAPI, OpenAI, and Gmail API integration.
- π€ AI-Powered Email Analysis - Uses OpenAI's GPT-4 to analyze incoming emails and determine if a response is needed
- π¬ Gmail Integration - Seamless OAuth2 integration with Gmail API for reading and sending emails
- π Smart Reply Generation - Automatically drafts professional and contextually appropriate email responses
- π FastAPI Backend - RESTful API for managing email operations with built-in authentication
- π Email Threading - Keeps track of email conversations and maintains proper threading
- π Automated Workflow - Processes unread emails in batches with configurable limits
- π― Intelligent Filtering - Automatically skips spam, newsletters, and automated notifications
- β Read Status Management - Marks emails as read after processing
- Backend Framework: FastAPI - Modern, fast web framework
- AI/LLM: OpenAI API - GPT-4o-mini for email analysis and response generation
- Email Service: Gmail API - Gmail integration with OAuth2
- Data Validation: Pydantic - Data parsing and validation
- AI Framework: Pydantic AI - Agentic AI workflows
- Environment Management: python-dotenv - Environment variables
- Python 3.8 or higher
- Gmail account with OAuth2 credentials
- OpenAI API key
git clone https://github.com/ShreyanshWarde/EmailAgent.git
cd EmailAgentpython -m venv venv
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activatepip install -r requirement.txtCreate a .env file in the root directory:
OPENAI_API_KEY=your_openai_api_key_here
GMAIL_CREDENTIALS_FILE=credentials.json- Go to Google Cloud Console
- Create a new project
- Enable Gmail API
- Create OAuth2 credentials (Desktop Application)
- Download credentials as JSON and save as
credentials.jsonin the project root
python app.pyThe server will start at http://localhost:8000
Available Endpoints:
GET /- Root endpoint with service informationGET /health- Health checkGET /docs- Interactive API documentation (Swagger UI)GET /redoc- ReDoc API documentationPOST /api/login- User authenticationPOST /api/process- Process unread emailsPOST /api/send-test- Send test emailGET /api/status- Service status
python main.pyThis will:
- Fetch all unread emails from your inbox
- Analyze each email with AI to determine if a response is needed
- Generate intelligent, contextually appropriate replies
- Send the replies automatically
- Mark processed emails as read
EmailAgent/
βββ app.py # FastAPI application setup and endpoints
βββ main.py # Main AI agent orchestrator
βββ gmail_service.py # Gmail API integration and email operations
βββ models.py # Pydantic data models for validation
βββ check.py # Utility functions for verification
βββ test_mark_read.py # Test suite for email marking functionality
βββ requirement.txt # Python dependencies
βββ credentials.json # Gmail OAuth2 credentials (not in repo)
βββ token.pickle # Gmail OAuth2 token cache (auto-generated)
βββ .gitignore # Git ignore configuration
βββ api/ # API routes and authentication modules
βββ scripts/ # Utility scripts
The main orchestrator that:
- Initializes the OpenAI client and Gmail service
- Fetches unread emails from Gmail
- Analyzes emails using AI
- Generates responses using OpenAI's GPT-4o-mini model
- Sends replies through Gmail
agent = EmailAIAgent()
agent.process_emails(max_emails=5) # Process up to 5 unread emailsHandles all Gmail API interactions:
authenticate()- OAuth2 authentication with Gmailget_unread_emails(max_results=10)- Fetch unread messagessend_email(to, subject, body)- Send email repliesmark_as_read(message_id)- Mark emails as readget_message_labels(message_id)- Retrieve message labels
Data validation models:
EmailContent- Validates incoming email dataDraftResponse- Validates AI-generated responsesEmailThread- Manages email conversation threads
The AI agent uses the following guidelines to determine if a reply is needed:
β Replies To:
- Important work emails
- Customer inquiries
- Personal messages requiring response
- Professional requests
β Skips:
- Spam and unsolicited emails
- Newsletters and notifications
- Automated alerts
- Marketing emails
The response tone adapts based on the original email and can be:
- Professional
- Friendly
- Formal
- Casual
1. Fetch unread emails
β
2. Analyze email with AI
β
3. Determine if reply needed
β
4. If yes: Generate response draft
β
5. Send reply via Gmail
β
6. Mark original email as read
β
7. Log success/failure
- β OAuth2 authentication for Gmail
- β Environment variables for sensitive data (API keys)
- β Input validation with Pydantic models
- β CORS middleware for API security
- β Token caching to minimize authentication requests
- β Error handling and logging throughout
Edit in main.py:
agent.process_emails(max_emails=5) # Adjust as neededEdit in main.py (line 36):
self.agent = Agent(
model='openai:gpt-4o-mini', # Or use gpt-3.5-turbo for cheaper testing
system_prompt="..."
)Edit in app.py (lines 26-32):
allow_origins=["http://localhost:3000", "http://localhost:8000"]python test_mark_read.pypython check.pyOnce the server is running, visit:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
Solution: Ensure your .env file exists and contains OPENAI_API_KEY=your_key_here
Solution:
- Regenerate OAuth2 credentials from Google Cloud Console
- Delete
token.pickleand re-authenticate - Ensure
credentials.jsonis in the project root
Solution:
- Check Gmail API is enabled in Google Cloud Console
- Verify OAuth2 scopes include
gmail.send - Review API quota limits
Solution:
- Verify OpenAI API key is valid and has credits
- Check internet connectivity
- Review OpenAI API status page
- Multi-language email support
- Advanced email classification system
- Email templates library
- Web UI dashboard
- Real-time email monitoring
- Email attachment handling
- Calendar integration for scheduling
- Analytics and reporting
- Multi-account support
- Custom AI response training
This project is open source and available under the MIT License.
Contributions are welcome! Please feel free to submit issues and pull requests to improve the project.
Shreyansh Warde
- GitHub: @ShreyanshWarde
- Start with
max_emails=1to test the workflow - Use GPT-3.5-turbo model for faster (and cheaper) testing
- Monitor API costs regularly with OpenAI dashboard
- Implement rate limiting in production environments
- Use email filtering before processing with the AI agent
For issues, questions, or suggestions, please open an issue on GitHub or contact the maintainer.