Skip to main content

Simple and fast mailing module for FastAPI with async support and Redis queue management

Project description

mailing2fast-fastapi

๐Ÿš€ Simple and fast mailing module for FastAPI with async support and Redis queue management

[!WARNING] Internal Use Notice

This package is designed and maintained by the Solautyc Team for internal use. While it is publicly available, it may not work as expected in all environments or use cases outside of our specific infrastructure. We do not provide support or guarantees for external usage, and we are not responsible for any issues that may arise from using this package in other contexts.

Use at your own risk. Contributions and feedback are welcome, but compatibility with external environments is not guaranteed.

Features

  • ๐Ÿ“ง Multiple SMTP Accounts: Configure multiple named email accounts (e.g., "support", "transactions", "notifications")
  • โšก Async Email Sending: Full async/await support with aiosmtplib
  • ๐Ÿ”„ Redis Queue Management: FIFO queue with automatic retry and dead letter queue
  • ๐ŸŽฏ Two Sending Modes:
    • Synchronous: Send and wait for success/failure response
    • Async Queue: Fire-and-forget with background worker processing
  • ๐Ÿšฆ Rate Limiting: Configurable rate limits (default: 100 emails/hour)
  • ๐Ÿ“ Jinja2 Templates: Built-in template support for HTML emails
  • ๐Ÿ“Ž Attachments: Easy attachment handling
  • ๐Ÿ” Automatic Retry: Exponential backoff for failed emails
  • โš™๏ธ Pydantic Settings: Type-safe configuration with environment variables
  • ๐ŸŽจ FastAPI Integration: Ready-to-use dependencies and lifecycle hooks

Installation

From PyPI (Recommended)

pip install mailing2fast-fastapi

From Source

# Clone the repository
git clone https://github.com/AngelDanielSanchezCastillo/mailing2fast-fastapi.git
cd mailing2fast-fastapi

# Install in development mode
pip install -e .

# Or install with dev dependencies
pip install -e ".[dev]"

Quick Start

1. Configure Environment Variables

Create a .env file:

# Default SMTP Account
MAIL_SMTP_ACCOUNTS__DEFAULT__HOST=smtp.gmail.com
MAIL_SMTP_ACCOUNTS__DEFAULT__PORT=587
MAIL_SMTP_ACCOUNTS__DEFAULT__USERNAME=your-email@gmail.com
MAIL_SMTP_ACCOUNTS__DEFAULT__PASSWORD=your-app-password
MAIL_SMTP_ACCOUNTS__DEFAULT__FROM_EMAIL=your-email@gmail.com
MAIL_SMTP_ACCOUNTS__DEFAULT__FROM_NAME=Your Name

# Support Account (optional)
MAIL_SMTP_ACCOUNTS__SUPPORT__HOST=smtp.gmail.com
MAIL_SMTP_ACCOUNTS__SUPPORT__PORT=587
MAIL_SMTP_ACCOUNTS__SUPPORT__USERNAME=support@yourcompany.com
MAIL_SMTP_ACCOUNTS__SUPPORT__PASSWORD=support-password
MAIL_SMTP_ACCOUNTS__SUPPORT__FROM_EMAIL=support@yourcompany.com
MAIL_SMTP_ACCOUNTS__SUPPORT__FROM_NAME=Support Team

# Redis Configuration
MAIL_REDIS__HOST=localhost
MAIL_REDIS__PORT=6379
MAIL_REDIS__DB=0

# Rate Limiting (optional)
MAIL_RATE_LIMIT__MAX_EMAILS_PER_HOUR=100
MAIL_RATE_LIMIT__MAX_EMAILS_PER_MINUTE=10

2. Basic Usage - Synchronous Sending

import asyncio
from mailing2fast_fastapi import EmailSender, EmailMessage

async def main():
    sender = EmailSender()
    
    email = EmailMessage(
        to=["recipient@example.com"],
        subject="Hello from mailing2fast!",
        body="This is a plain text email",
        html="<h1>This is an HTML email</h1>",
    )
    
    result = await sender.send_email(email)
    
    if result.is_success():
        print(f"Email sent! Message ID: {result.message_id}")
    else:
        print(f"Failed to send: {result.error}")

asyncio.run(main())

3. Async Queue Mode

import asyncio
from mailing2fast_fastapi import EmailQueue, EmailMessage, EmailWorker

async def main():
    # Start background worker
    worker = EmailWorker()
    await worker.start()
    
    # Queue emails (fire-and-forget)
    queue = EmailQueue()
    await queue.connect()
    
    email = EmailMessage(
        to=["recipient@example.com"],
        subject="Queued Email",
        body="This email will be sent by the background worker",
    )
    
    await queue.enqueue(email)
    print("Email queued successfully!")
    
    # Worker will process it in the background
    # Keep worker running...
    await asyncio.sleep(60)
    
    await worker.stop()
    await queue.disconnect()

asyncio.run(main())

4. FastAPI Integration

from fastapi import FastAPI, Depends
from mailing2fast_fastapi import (
    EmailMessage,
    EmailSender,
    EmailQueue,
    get_email_sender,
    get_email_queue,
    startup_email_worker,
    shutdown_email_worker,
)

app = FastAPI()

# Start/stop worker with app lifecycle
@app.on_event("startup")
async def startup():
    await startup_email_worker()

@app.on_event("shutdown")
async def shutdown():
    await shutdown_email_worker()

# Synchronous sending endpoint
@app.post("/send-email")
async def send_email(sender: EmailSender = Depends(get_email_sender)):
    email = EmailMessage(
        to=["user@example.com"],
        subject="Welcome!",
        html="<h1>Welcome to our service!</h1>",
    )
    
    result = await sender.send_email(email)
    return {"status": result.status, "message_id": result.message_id}

# Async queue endpoint
@app.post("/queue-email")
async def queue_email(queue: EmailQueue = Depends(get_email_queue)):
    email = EmailMessage(
        to=["user@example.com"],
        subject="Newsletter",
        html="<h1>Monthly Newsletter</h1>",
        smtp_account="support",  # Use specific account
    )
    
    await queue.enqueue(email)
    return {"status": "queued"}

Multiple SMTP Accounts

Configure different accounts for different purposes:

email = EmailMessage(
    to=["customer@example.com"],
    subject="Payment Confirmation",
    html="<h1>Payment received!</h1>",
    smtp_account="transactions",  # Use transactions account
)

Templates

Create Jinja2 templates in templates/emails/:

templates/emails/welcome.html:

<h1>Welcome, {{ name }}!</h1>
<p>Thank you for joining {{ company_name }}.</p>

Usage:

email = EmailMessage(
    to=["user@example.com"],
    subject="Welcome!",
    template_name="welcome.html",
    template_data={
        "name": "John Doe",
        "company_name": "Acme Corp"
    },
)

Rate Limiting

Rate limiting is enabled by default (100 emails/hour). Configure via environment variables:

MAIL_RATE_LIMIT__ENABLED=true
MAIL_RATE_LIMIT__MAX_EMAILS_PER_HOUR=100
MAIL_RATE_LIMIT__MAX_EMAILS_PER_MINUTE=10

Queue Management

Monitor queue status:

queue = EmailQueue()
await queue.connect()

stats = {
    "pending": await queue.get_queue_size(),
    "retry": await queue.get_retry_queue_size(),
    "failed": await queue.get_dlq_size(),
}
print(stats)

๐Ÿ“š Documentation

Module Structure

mailing2fast-fastapi/
โ”œโ”€โ”€ pyproject.toml
โ”œโ”€โ”€ MANIFEST.in
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ LICENSE
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ mailing2fast_fastapi/
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ”œโ”€โ”€ __version__.py
โ”‚       โ”œโ”€โ”€ settings.py       # Pydantic settings
โ”‚       โ”œโ”€โ”€ models.py          # Email schemas
โ”‚       โ”œโ”€โ”€ sender.py          # Email sender
โ”‚       โ”œโ”€โ”€ queue.py           # Redis queue
โ”‚       โ”œโ”€โ”€ worker.py          # Background worker
โ”‚       โ””โ”€โ”€ dependencies.py    # FastAPI deps
โ”œโ”€โ”€ docs/
โ”‚   โ”œโ”€โ”€ env.example
โ”‚   โ”œโ”€โ”€ usage.md
โ”‚   โ””โ”€โ”€ publishing.md
โ”œโ”€โ”€ examples/
โ”‚   โ”œโ”€โ”€ basic_usage.py
โ”‚   โ”œโ”€โ”€ async_queue.py
โ”‚   โ””โ”€โ”€ fastapi_integration.py
โ””โ”€โ”€ tests/
    โ”œโ”€โ”€ test_sender.py
    โ”œโ”€โ”€ test_queue.py
    โ””โ”€โ”€ test_integration.py

Acknowledgments

This project uses the following open-source packages:

  • FastAPI - Modern web framework (MIT License)
  • Pydantic - Data validation (MIT License)
  • Redis - Redis client (MIT License)
  • aiosmtplib - Async SMTP client (MIT License)
  • Jinja2 - Template engine (BSD License)

We are grateful to the maintainers and contributors of these projects.

License

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

Copyright (c) 2026 Angel Daniel Sanchez Castillo

Note: This package is designed and maintained by the Solautyc Team for internal use. While publicly available under MIT license, use at your own risk.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mailing2fast_fastapi-0.1.0.tar.gz (24.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mailing2fast_fastapi-0.1.0-py3-none-any.whl (20.0 kB view details)

Uploaded Python 3

File details

Details for the file mailing2fast_fastapi-0.1.0.tar.gz.

File metadata

  • Download URL: mailing2fast_fastapi-0.1.0.tar.gz
  • Upload date:
  • Size: 24.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for mailing2fast_fastapi-0.1.0.tar.gz
Algorithm Hash digest
SHA256 63d4d6502ee54e67cbc19422d39735407a0f811d06d28c46c186cdd0e862480b
MD5 6c476b05a3381c0b96f708623e6c7f96
BLAKE2b-256 a5b9dc2925d2e93b8509486269200ba3fe308d492b0099071a0779406a5878a9

See more details on using hashes here.

File details

Details for the file mailing2fast_fastapi-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for mailing2fast_fastapi-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9b0f777c6ad24b5309afacfd2bff8f7d97d34d19704fcfda383f0c9a7162fe78
MD5 325b3d32c963ea0b4e7919fb3e99b640
BLAKE2b-256 5e6fa53a1a85c941d185ebacd7ecf2854088f0dbfdff4d618218bca69b6df877

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page