How to Use Python FastAPI for Sending Emails

Posted by


In this tutorial, we will learn how to send emails using Python FastAPI. FastAPI is a modern web framework for building APIs quickly and efficiently. To send emails, we will use the smtplib library for sending emails and email.message for creating email messages.

Step 1: Install FastAPI and the necessary libraries
First, you need to install FastAPI and the necessary libraries by running the following command:

pip install fastapi uvicorn

Next, we need to install the smtplib library for sending emails:

pip install secure-smtplib

Step 2: Create a FastAPI application
Create a new Python file called main.py and add the following code to create a FastAPI application:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello World"}

Step 3: Send emails using smtplib library
Now, let’s add a new endpoint to our FastAPI application to send an email. Add the following code to the main.py file:

from fastapi import FastAPI
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

app = FastAPI()

SMTP_SERVER = "smtp.yourserver.com"
SMTP_PORT = 587
SMTP_USER = "your_email@example.com"
SMTP_PASSWORD = "your_password"

def send_email(to_email, subject, message):
    msg = MIMEMultipart()
    msg['From'] = SMTP_USER
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(message, 'plain'))

    server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    server.starttls()
    server.login(SMTP_USER, SMTP_PASSWORD)
    text = msg.as_string()
    server.sendmail(SMTP_USER, to_email, text)
    server.quit()

@app.get("/send_email")
def send_email_api(email: str, subject: str, message: str):
    send_email(email, subject, message)
    return {"message": "Email sent successfully"}

In the code above, we created a new endpoint /send_email that receives the email, subject, and message as query parameters and calls the send_email() function to send the email using the smtplib library.

Step 4: Start the FastAPI application
To start the FastAPI application, run the following command in the terminal:

uvicorn main:app --reload

Now, you can access the FastAPI application at http://localhost:8000. To send an email, you can make a GET request to http://localhost:8000/send_email?email=recipient@example.com&subject=Test&message=Hello.

That’s it! You have successfully learned how to send emails using Python FastAPI. Feel free to customize the email content and add more features to meet your requirements.

0 0 votes
Article Rating

Leave a Reply

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@casualchou
2 hours ago

Thank you so much !

@kailaslaxman1837
2 hours ago

Good one bro..

2
0
Would love your thoughts, please comment.x
()
x