Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

25 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ“ง MailApix API

Enterprise-grade async email delivery API with token-based access, quota controls, and template-driven messaging.

Python FastAPI PostgreSQL Redis License

Status: Build Production Documentation Version


๐Ÿ“‘ Table of Contents


๐ŸŽฏ Overview

MailApix API is a production-ready async email delivery backend built with FastAPI and PostgreSQL. It provides secure token-based access for users to send emails using their own SMTP credentials or the system's default service with quota-based protection.

Project Status: โœ… COMPLETE AND PRODUCTION READY

  • Build Status: โœ… SUCCESS
  • Features: โœ… FULLY IMPLEMENTED (8 endpoints)
  • Documentation: โœ… COMPLETE (API + Guides)
  • Deployment Ready: โœ… YES (Docker + Gunicorn)

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.10+
  • PostgreSQL 12+
  • Redis
  • Git

Installation

# Clone the repository
git clone https://github.com/Sumit0ubey/MailAPIX
cd MailApixAPI

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # or .venv\Scripts\activate on Windows

# Install dependencies
pip install -r requirements.txt

# Configure environment
# Create .env file with database and email credentials
cp .env.example .env

# Run the application
uvicorn MailApixAPI.main:app --reload

# In another terminal, run Celery
celery -A MailApixAPI.celery_app:celery_app worker --loglevel=info

The API will be available at http://localhost:8000
Documentation: http://localhost:8000/documentation


๐Ÿ“š Documentation

๐Ÿ“– Complete API Documentation

Comprehensive endpoint documentation with request/response examples, validation rules, and error scenarios.

๐Ÿ‘‰ View API Documentation

๐Ÿ“‹ This README

Project overview and quick reference guide.


โœจ Features

๐Ÿ‘ฅ User Management

  • โœ… User registration with token delivery
  • โœ… Token-based authentication
  • โœ… Token refresh via revoke keys
  • โœ… Account password protection

๐Ÿ“ง Email Delivery

  • โœ… Send with user SMTP credentials
  • โœ… Send with system SMTP fallback
  • โœ… Single or multi-recipient support
  • โœ… Quota-based rate limiting

๐ŸŽจ Template System

  • โœ… 5 email templates (0-4)
  • โœ… Custom HTML support
  • โœ… Dynamic variables
  • โœ… Fallback text support

๐Ÿ” Security

  • โœ… Token-gated routes
  • โœ… Password hardening
  • โœ… Quota protection
  • โœ… Email validation

๐Ÿ—๏ธ System Design

๐Ÿ“ High-Level Architecture

%%{init: {'themeCSS': '.cluster rect, .node rect, .node circle, .node ellipse, .node polygon, .edgeLabel rect, .actor, .labelBox, .note, .entityBox, .attributeBoxOdd, .attributeBoxEven, .er.entityBox, .er.attributeBoxOdd, .er.attributeBoxEven { fill: transparent !important; }'}}%%
graph TB
    Client["๐Ÿ‘ฅ Client Layer<br/>(Web/Mobile/CLI Apps)"]
    
    subgraph API["๐Ÿš€ API Gateway Layer<br/>(FastAPI + CORS Middleware)"]
        UserRouter["User Router"]
        EmailRouter["Email Router"]
        StatusRouter["Status Routes"]
    end
    
    subgraph Core["โš™๏ธ Core Services Layer"]
        Services["Services<br/>โ€ข UserServices<br/>โ€ข EmailService"]
        Queue["Task Queue<br/>(Celery)"]
        DB["Database Service<br/>PostgreSQL<br/>Async ORM<br/>SQLAlchemy"]
    end
    
    Redis["๐Ÿ”ด Redis<br/>(Broker & Backend)"]
    
    subgraph Ext["๐ŸŒ External Services"]
        SMTP["SMTP Service<br/>(Multi-Provider)"]
        Templates["Template Engine"]
        Logging["Logging System"]
    end
    
    EmailProviders["๐Ÿ“ง Email Providers<br/>(Gmail, Outlook, Yahoo, Zoho)"]
    
    Client -->|HTTP/REST| API
    API --> Services
    API --> Queue
    API --> DB
    Services --> Redis
    Queue --> Redis
    DB --> Redis
    Services --> SMTP
    Services --> Templates
    Services --> Logging
    SMTP --> EmailProviders
    
Loading

๐Ÿ”„ Data Flow Diagram

User Registration Flow

%%{init: {'themeCSS': '.cluster rect, .node rect, .node circle, .node ellipse, .node polygon, .edgeLabel rect, .actor, .labelBox, .note, .entityBox, .attributeBoxOdd, .attributeBoxEven, .er.entityBox, .er.attributeBoxOdd, .er.attributeBoxEven { fill: transparent !important; }'}}%%
sequenceDiagram
    participant Client
    participant API
    participant Services
    participant DB as PostgreSQL
    participant Queue as Celery Queue

    Client->>API: POST /users/<br/>(fullName, email, password)
    API->>Services: Validate Input
    Services->>Services: Generate Tokens<br/>(API Token, Revoke)
    Services->>DB: Create User<br/>(Store in DB)
    DB-->>Services: User Created โœ“
    Services-->>API: User Object + Tokens
    API-->>Client: HTTP 201 Created<br/>(token, revokeToken)
    
    API->>Queue: Task: Send Registration Email<br/>(via Celery)
    Queue-->>Client: (Processing Async)
Loading

Email Sending Flow (Async Processing)

%%{init: {'themeCSS': '.cluster rect, .node rect, .node circle, .node ellipse, .node polygon, .edgeLabel rect, .actor, .labelBox, .note, .entityBox, .attributeBoxOdd, .attributeBoxEven, .er.entityBox, .er.attributeBoxOdd, .er.attributeBoxEven { fill: transparent !important; }'}}%%
sequenceDiagram
    participant Client
    participant API
    participant Queue as Redis Queue
    participant Worker as Celery Worker
    participant SMTP

    Client->>API: POST /email/
    API->>API: Validate Token
    API->>API: Check Quota
    API->>API: Store Request in DB
    API-->>Client: HTTP 202 Accepted<br/>(job_id)
    
    API->>Queue: Enqueue Task<br/>(via Redis)
    Queue->>Worker: Dequeue Task
    Worker->>SMTP: Connect to SMTP Server
    Worker->>Worker: Render Template
    Worker->>SMTP: Send Email
    SMTP-->>Worker: Success โœ“
    Worker-->>Queue: Result (Status)
Loading

Token Refresh Flow

%%{init: {'themeCSS': '.cluster rect, .node rect, .node circle, .node ellipse, .node polygon, .edgeLabel rect, .actor, .labelBox, .note, .entityBox, .attributeBoxOdd, .attributeBoxEven, .er.entityBox, .er.attributeBoxOdd, .er.attributeBoxEven { fill: transparent !important; }'}}%%
sequenceDiagram
    participant Client
    participant API
    participant Services
    participant DB as PostgreSQL
    participant Queue as Celery Queue

    Client->>API: POST /users/newToken/{id}
    API->>Services: Verify User ID
    Services->>DB: Query User by ID
    DB-->>Services: User Info โœ“
    Services->>Services: Generate New Token
    Services->>DB: Update DB<br/>(Store New Token)
    DB-->>Services: Updated โœ“
    Services-->>API: New Token
    API-->>Client: HTTP 200 OK<br/>(newToken)
    
    Services->>Queue: Task: Revoke Old Token<br/>(Async)
    Queue-->>DB: Schedule Revoke
Loading

๐Ÿ”€ Component Interaction Diagram

%%{init: {'themeCSS': '.cluster rect, .node rect, .node circle, .node ellipse, .node polygon, .edgeLabel rect, .actor, .labelBox, .note, .entityBox, .attributeBoxOdd, .attributeBoxEven, .er.entityBox, .er.attributeBoxOdd, .er.attributeBoxEven { fill: transparent !important; }'}}%%
graph TB
    subgraph Router["๐ŸŽฎ FastAPI Router<br/>(Request Processing)"]
        UserR["User Router<br/>โ€ข register<br/>โ€ข getUser<br/>โ€ข newToken<br/>โ€ข revokeKey<br/>โ€ข secureAccount"]
        EmailR["Email Router<br/>โ€ข send<br/>โ€ข sendDefault"]
    end
    
    subgraph Services["โš™๏ธ Services Layer"]
        UserServ["UserServices<br/>โ€ข register()<br/>โ€ข getUser()<br/>โ€ข newToken()<br/>โ€ข revokeKey()<br/>โ€ข secureAccount()"]
        EmailServ["EmailService<br/>โ€ข validate_email()<br/>โ€ข send()<br/>โ€ข sendDefault()<br/>โ€ข renderTemplate()<br/>โ€ข getUserSMTP()"]
    end
    
    subgraph Data["๐Ÿ’พ Data Access Layer"]
        ORM["SQLAlchemy ORM<br/>(Async Session)"]
        Model["User Model"]
    end
    
    subgraph DB["๐Ÿ—„๏ธ Database"]
        DBConn["PostgreSQL<br/>Primary Connection"]
        Table["Users Table<br/>โ€ข id<br/>โ€ข email<br/>โ€ข apiToken<br/>โ€ข quotas<br/>โ€ข createdAt"]
    end
    
    Queue["๐Ÿ“ฆ Celery Queue<br/>(Redis)<br/>โ€ข revoke_token()<br/>โ€ข send_email()<br/>โ€ข notify_user()"]
    
    SMTP["๐Ÿ“ง SMTP Service<br/>(Multi-Provider)<br/>Gmail, Outlook,<br/>Yahoo, Zoho"]
    
    UserR -->|routes to| UserServ
    EmailR -->|routes to| EmailServ
    UserServ -->|uses| ORM
    EmailServ -->|uses| ORM
    ORM -->|maps| Model
    Model -->|queries| DBConn
    DBConn -->|accesses| Table
    UserServ -->|enqueues| Queue
    EmailServ -->|connects| SMTP
    Queue -->|processes async| EmailServ
    
Loading

๐Ÿ“Š Database Schema Diagram

%%{init: {'themeCSS': '.cluster rect, .node rect, .node circle, .node ellipse, .node polygon, .edgeLabel rect, .actor, .labelBox, .note, .entityBox, .attributeBoxOdd, .attributeBoxEven, .er.entityBox, .er.attributeBoxOdd, .er.attributeBoxEven { fill: transparent !important; }'}}%%
erDiagram
    USERS ||--o{ EMAIL_SESSIONS : sends
    USERS ||--o{ TOKENS : has
    
    USERS {
        string id PK "UUID"
        string fullName "String, not null"
        string email UK "String, unique, not null"
        string password "String, hashed"
        string apiToken UK "String, unique, not null"
        string revokeToken UK "String, unique, nullable"
        boolean isPaidUser "Boolean, default false"
        int numberOfEmailSend "Integer, default 0"
        int numberOfEmailCanSend "Integer, default 20"
        int defaultEmailSend "Integer, default 0"
        int defaultEmailCanSend "Integer, default 5"
        timestamp createdAt "TIMESTAMP with timezone"
    }
    
    EMAIL_SESSIONS {
        string id PK "UUID"
        string user_id FK "References Users.id"
        string recipient "Email recipient"
        string subject "Email subject"
        text body "Email body/HTML"
        string status "pending, sent, failed"
        timestamp created_at "When email was sent"
    }
    
    TOKENS {
        string id PK "UUID"
        string user_id FK "References Users.id"
        string token_value "Token value"
        string token_type "api_token, revoke_token"
        timestamp expires_at "Token expiration"
        boolean is_active "Active status"
    }
Loading

๐Ÿ” Authentication & Authorization Flow

%%{init: {'themeCSS': '.cluster rect, .node rect, .node circle, .node ellipse, .node polygon, .edgeLabel rect, .actor, .labelBox, .note, .entityBox, .attributeBoxOdd, .attributeBoxEven, .er.entityBox, .er.attributeBoxOdd, .er.attributeBoxEven { fill: transparent !important; }'}}%%
flowchart TD
    Start["๐Ÿ” API REQUEST<br/>WITH TOKEN HEADER"] --> Extract["Extract Bearer Token<br/>from Headers"]
    Extract --> Query["Query User by Token<br/>in Database"]
    Query --> Check{Token<br/>Valid?}
    
    Check -->|YES| Load["Load User Context<br/>into Request"]
    Check -->|NO| Reject["โŒ Return 401<br/>Unauthorized"]
    
    Load --> CheckQuota{Check Quotas<br/>& Permissions}
    
    CheckQuota -->|OK| Proceed["โœ… Proceed with<br/>Request"]
    CheckQuota -->|DENIED| QuotaError["โ›” Return 429<br/>Quota Limit Exceeded"]
    
    Proceed --> Success["Execute Handler"]
    Reject --> End1["End - Rejected"]
    QuotaError --> End2["End - Quota Error"]
    Success --> End3["End - Success"]
    
Loading

๐Ÿ“ˆ Scaling Architecture

%%{init: {'themeCSS': '.cluster rect, .node rect, .node circle, .node ellipse, .node polygon, .edgeLabel rect, .actor, .labelBox, .note, .entityBox, .attributeBoxOdd, .attributeBoxEven, .er.entityBox, .er.attributeBoxOdd, .er.attributeBoxEven { fill: transparent !important; }'}}%%
graph TB
    subgraph LB["๐Ÿ”„ Load Balancing Layer"]
        Proxy["Reverse Proxy<br/>(Nginx/HAProxy)"]
    end
    
    subgraph API["๐Ÿš€ API Servers<br/>(Horizontally Scalable)"]
        Instance1["FastAPI Instance 1<br/>(Gunicorn)"]
        Instance2["FastAPI Instance 2<br/>(Gunicorn)"]
        InstanceN["FastAPI Instance N<br/>(Gunicorn)"]
    end
    
    subgraph Data["๐Ÿ’พ Data Layer"]
        PG["PostgreSQL Primary"]
        PGRead1["Read Replica 1"]
        PGRead2["Read Replica N"]
    end
    
    subgraph Cache["โšก Cache & Queue Layer"]
        Redis["Redis Cluster<br/>โ€ข Task Queue<br/>โ€ข Result Backend<br/>โ€ข Caching<br/>โ€ข Sessions"]
    end
    
    subgraph Workers["๐Ÿ”ง Worker Layer"]
        Celery["Celery Workers<br/>(Async Processing)"]
    end
    
    Client["๐Ÿ‘ฅ Clients"]
    
    Client -->|HTTP/HTTPS| Proxy
    Proxy --> Instance1
    Proxy --> Instance2
    Proxy --> InstanceN
    
    Instance1 --> PG
    Instance2 --> PG
    InstanceN --> PG
    
    Instance1 --> PGRead1
    Instance2 --> PGRead2
    InstanceN --> PGRead1
    
    Instance1 --> Redis
    Instance2 --> Redis
    InstanceN --> Redis
    
    Redis --> Celery
    Celery --> Redis
    
Loading

๐Ÿ—๏ธ Architecture

Clean Layered Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚     FastAPI Routers                 โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚     Business Logic Layer            โ”‚
โ”‚     (Services)                      โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚     Data Access Layer               โ”‚
โ”‚     (Repositories + ORM)            โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚     Infrastructure                  โ”‚
โ”‚     (Database, Email, Cache)        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Design Principles

  • Async-First: Non-blocking I/O with asyncio
  • Separation of Concerns: Clear router โ†’ service โ†’ repository pattern
  • Dependency Injection: FastAPI's Depends() for loose coupling
  • Error Handling: Comprehensive exception handling with proper HTTP codes

๐Ÿ“Š Project Structure

MailApixAPI/
โ”‚
โ”œโ”€โ”€ ๐ŸŽฎ Routers/
โ”‚   โ”œโ”€โ”€ user.py              โ”‚ User registration & token management
โ”‚   โ””โ”€โ”€ email.py             โ”‚ Email sending endpoints
โ”‚
โ”œโ”€โ”€ โš™๏ธ Services/
โ”‚   โ”œโ”€โ”€ UserServices.py      โ”‚ User business logic
โ”‚   โ””โ”€โ”€ EmailService.py      โ”‚ Email delivery logic
โ”‚
โ”œโ”€โ”€ ๐Ÿ’พ Controller/
โ”‚   โ”œโ”€โ”€ database.py          โ”‚ Database connection & session
โ”‚   โ”œโ”€โ”€ models.py            โ”‚ SQLAlchemy ORM models
โ”‚   โ”œโ”€โ”€ schema.py            โ”‚ Pydantic request/response schemas
โ”‚   โ””โ”€โ”€ parser.py            โ”‚ Request parsers
โ”‚
โ”œโ”€โ”€ ๐ŸŽจ Templates/
โ”‚   โ”œโ”€โ”€ simple.py            โ”‚ Plain text template
โ”‚   โ”œโ”€โ”€ cool.py              โ”‚ HTML template 1
โ”‚   โ”œโ”€โ”€ amazing.py           โ”‚ HTML template 2
โ”‚   โ”œโ”€โ”€ impressive.py        โ”‚ HTML template 3
โ”‚   โ””โ”€โ”€ System/
โ”‚       โ”œโ”€โ”€ registration.py  โ”‚ Registration email
โ”‚       โ”œโ”€โ”€ packageplan.py   โ”‚ Upgrade email
โ”‚       โ””โ”€โ”€ tokenrevert.py   โ”‚ Token reset email
โ”‚
โ”œโ”€โ”€ ๐Ÿ“ฆ Tasks/
โ”‚   โ””โ”€โ”€ revoke_token_tasks.py โ”‚ Celery background tasks
โ”‚
โ”œโ”€โ”€ __init__.py          โ”‚ Package initialization
โ”œโ”€โ”€ main.py              โ”‚ FastAPI app initialization
โ”œโ”€โ”€ celery_app.py        โ”‚ Celery task queue setup  
โ”œโ”€โ”€ utils.py             โ”‚ Helper functions
โ”œโ”€โ”€ logger.py            โ”‚ Logging configuration        
โ”‚
โ””โ”€โ”€ .env                 โ”‚ Environment variables

๐Ÿ”Œ API Endpoints

๐Ÿ“ฅ User Management (GET)

Endpoint Purpose
GET /users/info Get user details
GET /users/upgrade Request upgrade plan

โœ๏ธ User Creation/Auth (POST)

Endpoint Purpose
POST /users/ Register new user
POST /users/revokeKey/{id} Generate revoke key
POST /users/newToken/{id} Generate new token

๐Ÿ”„ User Updates (PUT)

Endpoint Purpose
PUT /users/secureAccount/{id} Set account password

๐Ÿ“ง Email Sending (POST)

Endpoint Purpose
POST /email/ Send with user SMTP
POST /email/default Send with system SMTP

Query Parameters

Parameter Type Description
template_id int Template ID (0-4)
company_name string Company name
company_link string Company website
email_title string Email subject

๐Ÿ’พ Technology Stack

  • Framework: FastAPI (Python)
  • Database: PostgreSQL with asyncpg
  • ORM: SQLAlchemy (async)
  • Validation: Pydantic v2
  • Email: SMTP (smtplib)
  • Background Tasks: Celery + Redis
  • Deployment: Gunicorn + Uvicorn
  • API Docs: Swagger/OpenAPI

๐ŸŽจ Templates

ID Type Use Case
0 Plain Text Simple transactional emails
1 Professional Business communications
2 Modern Product notifications
3 Elegant Marketing campaigns
4 Custom Full HTML control

Template Variables

All templates support:

  • title - Email heading
  • content - Email body
  • company_name - Company name
  • company_link - Company website

๐Ÿšข Deployment

Production Setup

# Build container
docker build -t mailapix-api .

# Run with Gunicorn
gunicorn -k uvicorn.workers.UvicornWorker MailApixAPI.main:app \
  --workers 4 \
  --bind 0.0.0.0:8000

Environment Variables

# Database
DATABASE_USERNAME=postgres_user
DATABASE_PASSWORD=postgres_password
DATABASE_HOSTNAME=localhost
DATABASE_NAME=mailapix_db

# Email
SYSTEM_EMAIL=you@example.com
SYSTEM_EMAIL_PASSKEY=app_password

# Celery
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/1

Deployment Checklist

  • โœ… Use managed PostgreSQL (RDS, Cloud SQL)
  • โœ… Store secrets in environment variables
  • โœ… Enable HTTPS at reverse proxy
  • โœ… Configure rate limiting
  • โœ… Set up database backups
  • โœ… Monitor logs and errors
  • โœ… Use strong email passwords

๐Ÿ›ก๏ธ Security

Best Practices

  • ๐Ÿ” Never commit .env files or secrets
  • ๐Ÿ”„ Rotate SYSTEM_EMAIL_PASSKEY every 90 days
  • ๐Ÿ›ก๏ธ Use HTTPS in production
  • โ›” Configure CORS explicitly (not *)
  • ๐Ÿšฆ Implement rate limiting
  • ๐Ÿ“Š Monitor quota usage
  • ๐Ÿ”‘ Treat API tokens like passwords
  • ๐Ÿ“ง Validate email addresses

Security Policy

Have you found a security vulnerability? Please follow responsible disclosure:

๐Ÿ‘‰ Security Policy


๐Ÿ“ License

This project is licensed under the MIT License - see LICENSE for details.


๐Ÿ‘จโ€๐Ÿ’ป Author

Sumit Dubey


โญ Show Your Support

If you found this project helpful, useful, or interesting, please consider giving it a star on GitHub! Your support helps:

  • ๐Ÿš€ Reach more developers who need this solution
  • ๐Ÿ’ช Motivate continued development and improvements
  • ๐ŸŒŸ Build a stronger community around the project

๐Ÿ“š Additional Resources

About

A lightweight and efficient email-sending API built with FastAPI and Python's smtplib. This service provides endpoints to send emails securely via SMTP, making it ideal for integration into larger applications or automation workflows.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Used by

Contributors

Languages