FastAPI-Mail

1.6.2 · active · verified Sat Apr 11

fastapi-mail is a simple, lightweight library for sending emails in FastAPI applications. It integrates seamlessly with FastAPI's asynchronous nature and background tasks to prevent blocking the event loop. The current version is 1.6.2, and it maintains an active development pace with frequent minor updates and bug fixes addressing community needs.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `fastapi-mail` to send an HTML email asynchronously using FastAPI's `BackgroundTasks`. It uses environment variables for sensitive SMTP credentials and defines a simple endpoint to trigger an email send. Remember to replace placeholder values with your actual SMTP server details.

from fastapi import FastAPI, BackgroundTasks
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from pydantic import EmailStr
import os

app = FastAPI()

# Configure email connection settings
# It's recommended to use environment variables for sensitive data
conf = ConnectionConfig(
    MAIL_USERNAME=os.environ.get("MAIL_USERNAME", "your_email@example.com"),
    MAIL_PASSWORD=os.environ.get("MAIL_PASSWORD", "your_password"),
    MAIL_FROM=EmailStr(os.environ.get("MAIL_FROM", "your_email@example.com")),
    MAIL_PORT=int(os.environ.get("MAIL_PORT", 587)),
    MAIL_SERVER=os.environ.get("MAIL_SERVER", "smtp.gmail.com"),
    MAIL_FROM_NAME=os.environ.get("MAIL_FROM_NAME", "My FastAPI App"),
    MAIL_STARTTLS=bool(os.environ.get("MAIL_STARTTLS", True)),
    MAIL_SSL_TLS=bool(os.environ.get("MAIL_SSL_TLS", False)),
    USE_CREDENTIALS=bool(os.environ.get("USE_CREDENTIALS", True)),
    VALIDATE_CERTS=bool(os.environ.get("VALIDATE_CERTS", True)),
    TEMPLATE_FOLDER=None # Path to your Jinja2 templates, e.g., './templates'
)

@app.post("/send-email")
async def send_test_email(email_to: EmailStr, background_tasks: BackgroundTasks):
    # Create a message schema
    message = MessageSchema(
        subject="FastAPI Mail Test",
        recipients=[email_to], # List of recipients
        body="<p>This is a test email sent from <strong>FastAPI-Mail</strong>!</p>",
        subtype="html" # Can be "plain" or "html"
    )
    
    # Instantiate FastMail with the configuration
    fm = FastMail(conf)
    
    # Send the email using background tasks to avoid blocking the API response
    background_tasks.add_task(fm.send_message, message)
    
    return {"message": "Email has been scheduled for sending"}

view raw JSON →