FastAPI Email: Send Emails Like A Pro
FastAPI Email: Send Emails Like a Pro
Hey guys! Ever wanted to send emails from your FastAPI application? It’s actually super easy, and in this guide, I’m going to show you exactly how to do it. We’ll cover everything from setting up your environment to sending both simple and rich HTML emails. Let’s dive in!
Table of Contents
Setting Up Your Environment
First things first, let’s set up our environment. This involves installing FastAPI and a few other libraries that will help us with sending emails. Fire up your terminal and let’s get started.
Install FastAPI and Dependencies
To kick things off, you’ll need to install FastAPI itself, along with
uvicorn
(an ASGI server for running FastAPI apps), and
python-multipart
(for handling form data, which can be useful if you’re sending emails with attachments). Additionally, we’ll need a library to handle the actual email sending. We’ll use
pydantic-settings
for configuration and
fastapi-mail
for email handling.
Run these commands in your terminal:
pip install fastapi uvicorn python-multipart fastapi-mail pydantic-settings
Make sure everything installs correctly. If you run into any issues, double-check your Python environment and pip versions.
Project Structure
Let’s create a basic project structure to keep things organized. Create a directory for your project, and inside it, create a file named
main.py
. This is where our FastAPI application code will live.
mydir/
├── main.py
└── .env
Also, create a
.env
file. This is where we will keep our credentials.
Configuring Email Settings
Now that we have our environment set up, we need to configure our email settings. This involves setting up the email server details, such as the host, port, username, and password. We’ll use
pydantic-settings
to manage these settings.
Setting Up
.env
File
Open your
.env
file and add the following (replace the values with your actual email credentials):
MAIL_USERNAME="your_email@example.com"
MAIL_PASSWORD="your_email_password"
MAIL_FROM="your_email@example.com"
MAIL_PORT=587
MAIL_SERVER="smtp.example.com"
MAIL_STARTTLS=True
MAIL_SSL_TLS=False
Note
: Using environment variables keeps your sensitive information secure and out of your codebase. Always make sure to add your
.env
file to your
.gitignore
to prevent accidentally committing it to version control.
Creating a Settings Class
In your
main.py
file, create a settings class using
pydantic-settings
to load these environment variables. This class will automatically read the variables from your
.env
file.
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
mail_username: str
mail_password: str
mail_from: str
mail_port: int
mail_server: str
mail_starttls: bool
mail_ssl_tls: bool
model_config = SettingsConfigDict(env_file=".env")
settings = Settings()
This
Settings
class will now hold all your email configuration details, making it easy to access them throughout your application.
Building Your FastAPI App
With the environment and settings configured, let’s build the FastAPI application. We’ll create a simple endpoint that triggers sending an email.
Initializing FastAPI and Mail
First, import the necessary modules and initialize FastAPI and
FastMail
.
from fastapi import FastAPI, BackgroundTasks
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
app = FastAPI()
conf = ConnectionConfig(
MAIL_USERNAME=settings.mail_username,
MAIL_PASSWORD=settings.mail_password,
MAIL_FROM=settings.mail_from,
MAIL_PORT=settings.mail_port,
MAIL_SERVER=settings.mail_server,
MAIL_STARTTLS=settings.mail_starttls,
MAIL_SSL_TLS=settings.mail_ssl_tls,
USE_CREDENTIALS=True,
VALIDATE_CERTS=True
)
Here,
ConnectionConfig
is initialized with the settings we loaded from the
.env
file.
FastMail
will use this configuration to connect to your email server.
Creating an Email Sending Endpoint
Now, let’s create an endpoint that sends an email when called. We’ll use
BackgroundTasks
to send the email in the background, so the API doesn’t have to wait for the email to be sent before responding.
from pydantic import EmailStr
async def send_email(email: EmailStr, subject: str, body: str):
message = MessageSchema(
subject=subject,
recipients=[email],
body=body,
subtype="html" # Set to "html" for HTML emails
)
fm = FastMail(conf)
await fm.send_message(message)
@app.post("/send-email")
async def send_email_endpoint(
email: EmailStr,
subject: str,
body: str,
background_tasks: BackgroundTasks
):
background_tasks.add_task(send_email, email, subject, body)
return {"message": "Email sent in the background"}
In this code:
-
send_emailis anasyncfunction that takes the recipient’s email, subject, and body as arguments. It creates aMessageSchemaobject with this information and sends the email usingFastMail. -
The
/send-emailendpoint accepts the same arguments and usesBackgroundTasksto run thesend_emailfunction in the background. This ensures that the API remains responsive.
Running Your FastAPI App
To run your FastAPI app, use the following command:
uvicorn main:app --reload
This will start the server, and you can access your endpoint at
http://localhost:8000/send-email
.
Sending HTML Emails
Sending HTML emails is similar to sending plain text emails, but you need to specify the
subtype
as `