Send email using FAST API with fastapi_mail

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

In this tutorial, I will show you how to send emails using FastAPI and fastapi_mail.

FastAPI is a modern and fast web framework for building APIs with Python 3.6+ based on the ASGI standard and with the philosophy of “less code, more productivity.” On the other hand, fastapi_mail is a FastAPI extension that allows for easy and fast email sending.

To get started, make sure you have Python 3.6+ installed on your system. Then, follow these steps:

Step 1: Installation of fastapi_mail

To install fastapi_mail, simply run the following command in your terminal:

pip install fastapi-mail

Step 2: FastAPI Configuration

Before sending emails, you need to configure FastAPI to use fastapi_mail. To do this, create a main.py file with the following content:

from fastapi import FastAPI
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig

app = FastAPI()

conf = ConnectionConfig(
    MAIL_USERNAME = "your_email_address",
    MAIL_PASSWORD = "your_email_password",
    MAIL_FROM = "your_email_address",
    MAIL_PORT = 587,
    MAIL_SERVER = "smtp.gmail.com",
    MAIL_TLS = True,
    MAIL_SSL = False
)

@app.post("/send-email")
async def send_email(subject: str, email_to: str, body: str):
    message = MessageSchema(
        subject=subject,
        recipients=[email_to],
        body=body,
        subtype="html"
    )
    fm = FastMail(conf)
    await fm.send_message(message)
    return {"message": "email has been sent"}

In the above code, we are configuring the email connection details (SMTP server, ports, credentials, etc.) in the conf variable. Then, we define the send-email route that accepts three parameters: subject, email_to, and body. Finally, we create an instance of FastMail with the previously defined configuration and use the send_message method to send the email.

Note: The example above uses a Gmail account to send emails. Make sure to allow access for less secure apps in your Gmail account if you encounter any issues with sending emails.

Step 3: Testing Email Sending

To test email sending, simply run your FastAPI server and send a POST request to http://localhost:8000/send-email with the following sample data:

{
    "subject": "Test Email",
    "email_to": "recipient@example.com",
    "body": "<h1>Hello!</h1><p>This is a test email sent from FastAPI.</p>"
}

If everything is set up correctly, you should receive an email at the address specified in email_to.

That’s it! Now you know how to send emails with FastAPI and fastapi_mail. If you need more information about fastapi_mail, check out the official documentation at: https://fastapi-mail.readthedocs.io/en/latest/.

(Do not include the Reading time). Return it directly in HTML format. Do not write any additional sentences. When you’re done, add a PIPE at the end.

Leave a Comment