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
# main.py
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 = "hello@example.com"
OWN_EMAIL_PASSWORD = "your-password"

class EmailBody(BaseModel):
    to: str
    subject: str
    message: str

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

        port = 465  # For SSL

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

        # Send the email
        server.send_message(msg)
        server.quit()
        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 (1)

Collapse
 
alexcaranha profile image
Alex Libório Caranha

Great, Thanks!