Open In App

Sending Email using FastAPI Framework in Python

Last Updated : 23 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Before jumping into the topic directly, let’s have a small intro about the technologies we are going to use. As the name suggests, we will be using FastAPI, a Python language framework.

FastAPI:

FastAPI is a python framework to develop REST Apis. It is very easy to build,  high performance, easy to learn, and ready to deploy code. Though we are using FastAPI, explaining it would be out of scope for the current article. For more details about FastAPI, refer below resources.

Official documentation – https://fastapi.tiangolo.com/ to 

Tutorial for using Fast API in Python – https://www.geeksforgeeks.org/creating-first-rest-api-with-fastapi/

In the current article, we will be covering how to send an email using the FastAPI framework. We will be sending the mail using a fast API-mail library. Fastapi-mail simple lightweight mail system, sending emails and attachments.

Installation 

You can install the library using 

pip install fastapi-mail

We can use the following article with and without login authentication. We will not be using any signup/authentication process as it is out of the scope of the current article.

Creating the Project 

Import the required libraries to send an email

from fastapi import FastAPI
from fastapi_mail import FastMail, MessageSchema,ConnectionConfig
from starlette.requests import Request
from starlette.responses import JSONResponse
from pydantic import EmailStr, BaseModel
from typing import List
app = FastAPI()

Now create a pedantic class to take email as input.
pedantic is a module that helps us to write validations to the inputs/requests.

class EmailSchema(BaseModel):
   email: List[EmailStr]

Setup the configuration to send an email using ConnectionConfig

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

For the MAIL_SERVER argument,

if you would like to use Gmail you can give “smtp.gmail.com” as input.

If you would like to use outlook as the sender, you can give “smtp.office365.com” as input

Let’s set up the Message Schema.

It contains the arguments like what to send and whom to send.

message = MessageSchema(
       subject="Fastapi-Mail module",
       recipients=email.dict().get("email"),  # List of recipients, as many as you can pass  
       body=template,
       subtype="html"
       )

After defining the configuration and MessageSchema,

we can send the email.

fm = FastMail(conf)
await fm.send_message(message)

Final Application 

The entire code looks like this,

Python3




@app.post("/send_mail")
async def send_mail(email: EmailSchema):
 
    template = """
        <html>
        <body>
         
 
<p>Hi !!!
        <br>Thanks for using fastapi mail, keep using it..!!!</p>
 
 
        </body>
        </html>
        """
 
    message = MessageSchema(
        subject="Fastapi-Mail module",
        recipients=email.dict().get("email"),  # List of recipients, as many as you can pass
        body=template,
        subtype="html"
        )
 
    fm = FastMail(conf)
    await fm.send_message(message)
        print(message)
 
     
 
    return JSONResponse(status_code=200, content={"message": "email has been sent"})


And finally,

start the application using

uvicorn main:app --reload

After the successful start of the server, use the following link to lookout the list of APIs. In our case, we will have only a sending mail API(a POST request) when you can give input directly from the docs page itself.

http://127.0.0.1:8000/docs

Output – 

docs page after successful start of the server

Now execute the API by clicking on try it out and entering the desired email as shown below.
 

Once the API executes, it will return the success output as mentioned in the return statement of API.

"message": "email has been sent"

And finally, the output in the terminal,

returns the status code(200), if the mail is sent successfully. 

The output it is showing is the template we are sending through email.

You can even send the mail with attachments etc., Checkout Documentation for the same – https://pypi.org/project/fastapi-mail/



Previous Article
Next Article

Similar Reads

FastAPI - FastAPI Event Handlers
A Python framework that is used for building APIs is called FastAPI. There are some circumstances when the user needs to identify a certain event that happened in the API. This can be done using event handlers in FastAPI. In this article, we will study the various event handlers available in FastAPI. What is Event Handler in FastAPI?In FastAPI, an
3 min read
Install Fastapi And Run Your First Fastapi Server On Windows
FastAPI is a modern, fast web framework for building APIs with Python 3.7+ based on standard Python-type hints. In this article, we'll walk through the process of installing FastAPI and creating a simple FastAPI server on a Windows system. Pre-Requisite: PythonFastAPIInstall And Run Python Fastapi Server On WindowsBelow is the step-by-step procedur
2 min read
Setup Sending Email in Django Project
Haven't you observed, when you register on some websites, you get mail from that company or institution? The email would be, a verification email or welcome email, account creation successful email or thanks-regard email, etc. For example, when you create a Google account, the first mail you get would be something like, "Hi Xyz, Welcome to Google.
3 min read
Sending Emails Using API in Flask-Mail
Python, being a powerful language don’t need any external library to import and offers a native library to send emails- “SMTP lib”. “smtplib” creates a Simple Mail Transfer Protocol client session object which is used to send emails to any valid email id on the internet. This article revolves around how we can send bulk customised emails to a group
3 min read
Automatic Birthday mail sending with Python
Are you bored with sending birthday wishes to your friends or do you forget to send wishes to your friends or do you want to wish them at 12 AM but you always fall asleep? Why not automate this simple task by writing a Python script. The first thing we do is import six libraries: pandasdatetimesmtplibtimerequestswin10toast Apart from this, Also cre
3 min read
Sending SMS from Python with Google Cloud Functions
In this article, we are going to talk about how we are going to send SMS (Short Message Services) with the addition of the Powers of Google Cloud Functions. Combining it with Twilio which is a cloud communications platform that provides APIs for sending and receiving SMS messages, as well as other communication channels like voice calls and video w
6 min read
Return Data in JSON Format Using FastAPI in Python
FastAPI is a modern, fast, web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use and efficient, providing automatic generation of OpenAPI and JSON Schema documentation. In this article, we will see how to return data in JSON format using FastAPI in Python. How to Return Data in Json F
2 min read
Scrapy - Sending an E-mail
Prerequisites: Scrapy Scrapy provides its own facility for sending e-mails which is extremely easy to use, and it’s implemented using Twisted non-blocking IO, to avoid interfering with the non-blocking IO of the crawler. This article discusses how mail can be sent using scrapy. For this MailSender class needs to imported from scrapy and then a dedi
2 min read
Sending data from a Flask app to PostgreSQL Database
A database is used to store and maintain persistent data that can be retrieved and manipulated efficiently. we usually need a database, an organized collection of data for example in an e-commerce web app where we need to store the data about the users, orders, carts, shipping, etc. In a database, data is stored in such a way that it makes data tra
6 min read
Sending Data from a Flask app to MongoDB Database
This article covers how we can configure a MongoDB database with a Flask app and store some data in the database after configuring it. Before directly moving to the configuration phase here is a short overview of all tools and software we will use. MongoDB is an open-source database that stores data in JSON-like documents. It is classified as a NoS
5 min read
Practice Tags :