How to Send Email in Background with FastAPI
In FastAPI, you can send emails in the background using the
BackgroundTasks utility. Add a background task to your endpoint that calls an email sending function, so the API response returns immediately while the email sends asynchronously.Syntax
Use BackgroundTasks from fastapi to run functions after returning a response. Inject it as a parameter in your path operation function, then add your email sending function to it with background_tasks.add_task(your_function, args).
BackgroundTasks: FastAPI class to schedule background work.add_task(): Method to add a function to run after response.your_function: The function that sends the email.
python
from fastapi import BackgroundTasks def send_email(email_to: str, subject: str, body: str): # Your email sending logic here pass def endpoint(background_tasks: BackgroundTasks): background_tasks.add_task(send_email, "user@example.com", "Hello", "Welcome!") return {"message": "Email will be sent in background"}
Example
This example shows a FastAPI app that sends an email in the background when you call the /send-email endpoint. The API responds immediately, while the email sending runs asynchronously.
python
from fastapi import FastAPI, BackgroundTasks import time app = FastAPI() def send_email(email_to: str, subject: str, body: str): # Simulate email sending delay time.sleep(5) print(f"Email sent to {email_to} with subject '{subject}'") @app.post("/send-email") async def send_email_endpoint(background_tasks: BackgroundTasks): background_tasks.add_task(send_email, "user@example.com", "Welcome", "Thanks for signing up!") return {"message": "Email is being sent in the background"}
Output
{"message": "Email is being sent in the background"}
# After 5 seconds in console: Email sent to user@example.com with subject 'Welcome'
Common Pitfalls
- Not using
BackgroundTasksand calling the email function directly blocks the API response until email sending finishes. - Forgetting to add the task with
background_tasks.add_task()means the email won't send asynchronously. - Running blocking code like
time.sleep()in async endpoints without background tasks causes slow responses. - Not handling exceptions inside the background task can cause silent failures.
python
from fastapi import FastAPI import time app = FastAPI() def send_email(email_to: str): time.sleep(5) # Blocking call print(f"Email sent to {email_to}") @app.post("/wrong-way") async def wrong_way(): send_email("user@example.com") # Blocks response return {"message": "Email sent"} from fastapi import BackgroundTasks @app.post("/right-way") async def right_way(background_tasks: BackgroundTasks): background_tasks.add_task(send_email, "user@example.com") return {"message": "Email will be sent in background"}
Quick Reference
- Import
BackgroundTasksfromfastapi. - Inject
background_tasks: BackgroundTasksin your endpoint. - Add your email function with
background_tasks.add_task(). - Keep email sending code separate and handle exceptions inside it.
- Use background tasks to keep API responses fast and non-blocking.
Key Takeaways
Use FastAPI's BackgroundTasks to send emails without blocking API responses.
Add your email sending function to background tasks with add_task() inside the endpoint.
Avoid calling blocking email code directly in async endpoints to keep responses fast.
Handle errors inside background tasks to avoid silent failures.
BackgroundTasks help improve user experience by sending emails asynchronously.