High-Performance Python Web•Async Python Framework

How to Send Transactional Emails in FastAPI with Mailofly

Send non-blocking transactional emails, order confirmations, and security alerts in FastAPI applications using the Mailofly Python SDK and BackgroundTasks.

pip install mailofly fastapi uvicorn
Setup Tutorial

Get Up and Running in 3 Easy Steps

01

Install Mailofly Python SDK

Install `mailofly` alongside `fastapi` using pip or Poetry.

02

Initialize the Mailofly client

Create a reusable client instance passing your `MAILOFLY_API_KEY` environment variable.

03

Schedule via BackgroundTasks

Use FastAPI's native `BackgroundTasks.add_task` to send transactional emails asynchronously without increasing API latency.

Production-Ready Code Example

Copy and paste into your project. Fully typed and tested.

main.py
import os
from fastapi import FastAPI, BackgroundTasks, HTTPException
from pydantic import BaseModel, EmailStr
from mailofly import Mailofly

app = FastAPI(title="FastAPI Email Service")
client = Mailofly(api_key=os.environ.get("MAILOFLY_API_KEY"))

class EmailSchema(BaseModel):
    email: EmailStr
    name: str

def send_welcome_email(email: str, name: str):
    """Worker task executed in background thread pool."""
    client.emails.send(
        sender="Acme <support@yourdomain.com>",
        to=email,
        subject=f"Welcome to Acme, {name}!",
        html=f"<h3>Hello {name},</h3><p>Your account is ready to use.</p>",
    )

@app.post("/register")
async def register_user(user: EmailSchema, background_tasks: BackgroundTasks):
    # Perform user registration logic...
    
    # Schedule email send in background without blocking API response
    background_tasks.add_task(send_welcome_email, user.email, user.name)
    
    return {"status": "success", "message": "User registered and email queued."}
Why Developers Love It

Engineered for FastAPI

Non-Blocking Async Performance

Using FastAPI BackgroundTasks ensures your HTTP endpoints return immediately to clients in sub-10ms while the email dispatches asynchronously.

Native Python Pydantic Support

Validate recipient emails automatically with Pydantic's EmailStr before triggering delivery.

Built-In Bounce & Suppression Radar

Mailofly protects your sender domain by blocking sends to previously hard-bounced addresses automatically.

Got Questions?

Frequently Asked Questions about FastAPI

The Mailofly Python SDK performs synchronous HTTP requests under the hood. Wrapping sends in FastAPI's BackgroundTasks executes them in a thread pool, preventing any blocking of your application's asynchronous event loop.

Start Sending from FastAPI in Minutes

3,000 free emails every month. Copy your API key, run the code snippet, and watch your delivery logs in real time.