DEV Community

Cover image for How to send emails with FastAPI
Nelson Hernández
Nelson Hernández

Posted on


How to send emails with FastAPI

In this example we will send an email through a POST type endpoint that will receive the information from the recipient

pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode
from fastapi import FastAPI
from fastapi.exceptions import HTTPException
from pydantic import BaseModel
from smtplib import SMTP_SSL
from email.mime.text import MIMEText

app = FastAPI()

OWN_EMAIL_PASSWORD = "your-password"

class EmailBody(BaseModel):
    to: str
    subject: str
    message: str"/email")
async def send_email(body: EmailBody):
        msg = MIMEText(body.message, "html")
        msg['Subject'] = body.subject
        msg['From'] = f'Denolyrics <{OWN_EMAIL}>'
        msg['To'] =

        port = 465  # For SSL

        # Connect to the email server
        server = SMTP_SSL("", port)
        server.login(OWN_EMAIL, OWN_EMAIL_PASSWORD)

        # Send the email
        return {"message": "Email sent successfully"}

    except Exception as e:
        raise HTTPException(status_code=500, detail=e)
Enter fullscreen mode Exit fullscreen mode

Run project

uvicorn main:app --reload --port 8000
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git