DEV Community

Dillion Huston
Dillion Huston

Posted on

Adding SMTP Email Notifications to FastAPI Using smtplib and Environment Variables

In my Task Automation API, I added email notification support using Python’s smtplib. The setup is minimal, uses no extra packages, and leverages environment variables to securely manage SMTP credentials.

Here’s a breakdown of the implementation, inspired by this commit:

View commit on GitHub

Email Sending Function with smtplib

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os

def send_email(recipient: str, subject: str, body: str):
    sender = os.getenv("SMTP_SENDER")
    password = os.getenv("SMTP_PASSWORD")
    smtp_server = os.getenv("SMTP_SERVER")
    smtp_port = int(os.getenv("SMTP_PORT", 587))

    msg = MIMEMultipart()
    msg["From"] = sender
    msg["To"] = recipient
    msg["Subject"] = subject
    msg.attach(MIMEText(body, "plain"))

    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(sender, password)
        server.sendmail(sender, recipient, msg.as_string())
Enter fullscreen mode Exit fullscreen mode

Environment Variables Setup

To keep secrets out of the codebase, define these in your .env file or server environment:

  • SMTP_SENDER: Your email address
  • SMTP_PASSWORD: SMTP password or app-specific password
  • SMTP_SERVER: SMTP host, e.g., smtp.gmail.com
  • SMTP_PORT: Port number, usually 587

How I Use It

After a user schedules a task, once and it’s validated, I call send_email to notify them:

send_email(
    recipient=current_user.email,
    subject="File Upload Successful",
    body=f"Your file {file.filename} was uploaded and verified."
)
Enter fullscreen mode Exit fullscreen mode

Why This Approach?

  • No external dependencies
  • Secure configuration with environment variables
  • Easy to extend for HTML emails or attachments later

Wrap Up

Adding SMTP email with smtplib is a lightweight, effective way to send notifications in your FastAPI app. This pattern fits nicely in automation workflows like mine.

Check out the full commit for details:

GitHub link

If you need help integrating emailing or environment management in your project, let me know.

Top comments (0)