A production-ready FastAPI email service with enterprise-grade security, authentication, and comprehensive monitoring features.
Get started in minutes:
# Clone and install
git clone <repository-url>
cd email-api
pip install -r requirements.txt
# Configure environment
cp .env.example .env
# Edit .env with your email credentials
# Generate security keys
python -c "import secrets; print(secrets.token_urlsafe(32))"
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
# Run the application
python main_secure.pyπ Full Documentation:
- Quick Start Guide - 5-minute setup
- Security API Documentation - Complete reference
- API Usage Examples - Code examples
- Deployment Guide - Production deployment
- API Key Authentication: Secure authentication with role-based access control
- Rate Limiting: Configurable per-API key limits to prevent abuse
- Input Validation: Comprehensive sanitization and validation
- Security Headers: CSP, XSS protection, HTTPS enforcement
- Audit Logging: Complete request/response tracking
- Dynamic Email Support: Multiple email accounts per API key
- Encrypted Credentials: Secure storage of email credentials
- Batch Operations: Efficient bulk email management
- Advanced Filtering: Date ranges, categories, and custom filters
- Read Status Management: Mark emails as read/unread
- Database Support: PostgreSQL (production) and SQLite (development)
- Monitoring: Health checks, metrics, and structured logging
- Scalability: Docker support and cloud deployment ready
- High Availability: Load balancing and failover support
# Create API key
curl -X POST "http://localhost:8000/api/v1/api-keys" \
-H "Content-Type: application/json" \
-d '{
"name": "My API Key",
"scopes": ["read", "write"],
"rate_limit_per_minute": 60
}'# Send email
curl -X POST "http://localhost:8000/api/v1/emails" \
-H "Authorization: Bearer your_key:your_secret" \
-H "Content-Type: application/json" \
-d '{
"receiver_email": "user@example.com",
"subject": "Hello",
"body": "Test message"
}'
# Get emails
curl -X GET "http://localhost:8000/api/v1/emails?filter_by=today" \
-H "Authorization: Bearer your_key:your_secret"# Security
SECRET_KEY=your-super-secret-key
ENCRYPTION_KEY=your-encryption-key
# Email
GMAIL_EMAIL=your-email@gmail.com
GMAIL_APP_PASSWORD=your-app-password
# Database
DATABASE_URL=postgresql://user:pass@localhost/email_api
# Environment
ENVIRONMENT=production- Enable 2FA on your Google account
- Generate App Password: Google Account β Security β 2-Step Verification β App Passwords
- Use the app password in your
.envfile
- Go to Account settings β Security β App passwords
- Generate new password for your app
- Use in
.envfile
# Environment setup
export ENVIRONMENT=production
export DATABASE_URL=postgresql://user:pass@localhost/email_api
# Run with Gunicorn
gunicorn main_secure:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000# docker-compose.yml
version: '3.8'
services:
email-api:
build: .
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://postgres:password@db:5432/email_api
- SECRET_KEY=your-secret-key
- ENVIRONMENT=production
depends_on:
- db
db:
image: postgres:15
environment:
- POSTGRES_DB=email_api
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password- Render: Use
render.yamlfor one-click deployment - AWS ECS: Container orchestration with auto-scaling
- Google Cloud Run: Serverless deployment
- Azure Container Instances: Cloud-based containers
- API key-based authentication with proper validation
- Role-based access control (read, write, admin scopes)
- Secure credential hashing and validation
- JWT support for future extensibility
- Pydantic schemas for all request/response models
- Email format validation and sanitization
- Subject and body content filtering
- Protection against header injection attacks
- Per-API key rate limiting (configurable limits)
- IP-based fallback rate limiting
- Real-time rate limit headers in responses
- Comprehensive audit logging and metrics
- Encrypted storage of email credentials
- Environment-based configuration management
- HTTPS enforcement for production
- Comprehensive security headers
# System health
curl http://localhost:8000/health
# Application metrics
curl -X GET "http://localhost:8000/api/v1/metrics" \
-H "Authorization: Bearer your_key:your_secret"- Structured Logging: JSON-formatted logs for easy parsing
- Request Tracking: Complete request/response audit trails
- Security Events: Authentication failures and rate limit hits
- Performance Metrics: Response time and throughput tracking
- Prometheus: Metrics collection and alerting
- ELK Stack: Log aggregation and analysis
- Datadog: Cloud monitoring and APM
- Grafana: Visualization and dashboards
pytest tests/# Format code
black .
isort .
# Lint code
flake8 .
# Type checking
mypy .# Install development dependencies
pip install -r requirements-dev.txt
# Run with auto-reload
uvicorn main_secure:app --reload --host 0.0.0.0 --port 8000| Document | Description | Audience |
|---|---|---|
| QUICK_START.md | 5-minute setup guide | Everyone |
| SECURITY_API_DOCUMENTATION.md | Complete API reference | Developers |
| API_USAGE_EXAMPLES.md | Code examples | Developers |
| DEPLOYMENT_GUIDE.md | Production deployment | DevOps |
Error: Invalid or inactive API key
Solution: Check API key format and ensure it's active
Error: Rate limit exceeded
Solution: Wait or increase rate limits in API key settings
Error: Failed to send email
Solution: Verify email credentials and app password
# Enable debug logging
export LOG_LEVEL=DEBUG
export ENVIRONMENT=development
# Run with debug
python main_secure.py- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
- Follow PEP 8 style guidelines
- Add type hints for all new code
- Include comprehensive tests
- Update documentation for new features
- Ensure security best practices
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Documentation: Check the comprehensive docs in this repository
- Issues: Report bugs on GitHub Issues
- Security: Contact support for security concerns
- Features: Request new features via GitHub issues
- Discussions: GitHub Discussions for general questions
- Stack Overflow: Tag your questions with
secure-email-api - Discord: Join our community server (link in README)
- OAuth2 support for email providers
- Advanced email filtering and search
- Webhook support for email events
- Multi-factor authentication for API keys
- Email templates and campaigns
- Attachment support
- Advanced analytics and reporting
- Rate limit analytics dashboard
- Microservices architecture
- GraphQL API
- Real-time email synchronization
- Advanced security features (IP whitelisting, etc.)
Built with β€οΈ for secure, reliable email operations. π§β¨
Use this repo as a template to deploy a Python FastAPI service on Render.
See https://render.com/docs/deploy-fastapi or follow the steps below:
-
You may use this repository directly or create your own repository from this template if you'd like to customize the code.
-
Create a new Web Service on Render.
-
Specify the URL to your new repository or this repository.
-
Render will automatically detect that you are deploying a Python service and use
pipto download the dependencies. -
Specify the following as the Start Command.
uvicorn main_secure:app --host 0.0.0.0 --port $PORT -
Click Create Web Service.
Or simply click:
Thanks to Harish for the inspiration to create a FastAPI quickstart for Render and for some sample code!