Learn how to send emails using Python FastAPI with step-by-step instructions. This guide includes code examples for sending emails with SMTP, HTML email templates, attachments, to multiple recipients, and more.

We are using the Python standard module smtplib. The smtplib is helping to connect the SMTP server and send emails.

Navigate to the desired topic by clicking on the items in the table of contents below.

Install Python Packages

First, we can create a test FastAPI route to send an email. Install the FastAPI and uvicorn modules.

pip install fastapi "uvicorn[standard]"

Create SandBox SMTP Email Account

MailMug.net provides a free SMTP account. You can easily test the mail function from your local or production server without sending it to a real email.

SMPT Sandbox account for php flight

Create an account now (MailMug.net). Then start testing.

FastAPI Send Simple Email By SMTP

Create a main.py file then add the following code.

from fastapi import FastAPI
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
 
app = FastAPI()
 
port = 2525
smtp_server = "smtp.mailmug.net"
login = "username here" # paste your login generated by mailmug
password = "pass here" # paste your password generated by mailmug
 
sender_email = "mailmug@example.com"
receiver_email = "new@example.com"
message = MIMEMultipart("alternative")
message["Subject"] = "Test subject"
message["From"] = sender_email
message["To"] = receiver_email
 
 
@app.get("/send-email")
def send_email():
 
     # write the HTML part
    html = """\
        <html>
        <body>
            <p>Hi,<br>
            This is the test email</p>
        </body>
        </html>
        """
    part = MIMEText(html, "html")
    message.attach(part)
 
    server = smtplib.SMTP(smtp_server, port)
    server.set_debuglevel(1)
    server.esmtp_features['auth'] = 'LOGIN DIGEST-MD5 PLAIN'
    server.login(login, password)
    server.sendmail(
        sender_email, receiver_email, message.as_string()
    )
 
 
    return {"msg":"send mail"}

Then execute the following command from the terminal to start the server.

uvicorn main:app --reload

Finally, navigate http://127.0.0.1:8000 from your browser.

How to Send Email to Multiple Recipients From Python FastAPI?

We can send emails to multiple recipients by adding an email address list to receiver_email in SMTPlib.

receiver_email =  ["new@example.com", "new1@example.com"]

Complete Code:-

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

app = FastAPI()

port = 2525 
smtp_server = "smtp.mailmug.net"
login = "username here" # paste your login generated by mailmug
password = "pass" # paste your password generated by mailmug

sender_email = "mailmug@example.com"
receiver_email =  ["new@example.com", "new1@example.com"]
message = MIMEMultipart("alternative")
message["Subject"] = "Test subject"
message["From"] = sender_email

if isinstance(receiver_email, str):
    message["To"] = receiver_email
else:
    message["To"] = ", ".join(receiver_email)


@app.get("/send-email")
def send_email():

     # write the HTML part
    html = """\
        <html>
        <body>
            <p>Hi,<br>
            This is the test email</p>
        </body>
        </html>
        """
    part = MIMEText(html, "html")
    message.attach(part)

    server = smtplib.SMTP(smtp_server, port)
    server.set_debuglevel(1)
    server.esmtp_features["auth"] = "LOGIN DIGEST-MD5 PLAIN"
    server.login(login, password)
    server.sendmail(
        sender_email, receiver_email, message.as_string()
    )


    return {"msg":"send mail"} 
Multiple Recipients From Python FastAPI

How to Add Bcc, Cc in Python FastAPI Email?

Pass ‘Cc‘ or ‘Bcc‘ to the MIMEMultipart message. It will automatically add to the email header part.

Example code:

message["Bcc"] = "bcc@example.com"
message["Cc"] = "cc@example.com"
Bcc, Cc in Python FastAPI Email

How to Send Python FastAPI Emails With Attached Files?

We can send emails with files by MIMEApplication class. The MIMEApplication class is used to encode nontext characters. It is encoding to base64. Read file data and store data in the MIMEApplication object. Attach multiple files by file array iteration.

from fastapi import FastAPI
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from os.path import basename

app = FastAPI()

port = 2525 
smtp_server = "smtp.mailmug.net"
login = "user" # paste your login generated by mailmug
password = "pass" # paste your password generated by mailmug

sender_email = "mailmug@example.com"
receiver_email =  ["new@example.com", "new1@example.com"]
message = MIMEMultipart("alternative")
message["Subject"] = "Test subject"
message["From"] = sender_email

if isinstance(receiver_email, str):
    message["To"] = receiver_email
else:
    message["To"] = ", ".join(receiver_email)

message["Bcc"] = "bcc@example.com"
message["Cc"] = "cc@example.com"


@app.get("/send-email")
def send_email():

     # write the HTML part
    html = """\
        <html>
        <body>
            <p>Hi,<br>
            This is the test email</p>
        </body>
        </html>
        """
    part = MIMEText(html, "html")
    message.attach(part)

    files = ['path/to/my.jpg']
    for f in files:
        with open(f, "rb") as fil:
            file_part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        file_part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        message.attach(file_part)

    server = smtplib.SMTP(smtp_server, port)
    server.set_debuglevel(1)
    server.esmtp_features['auth'] = 'LOGIN DIGEST-MD5 PLAIN'
    server.login(login, password)
    server.sendmail(
        sender_email, receiver_email, message.as_string()
    )
    server.close()


    return {"msg":"send mail"}

Change SMTPlib Debug Option

The set_debuglevel method in the smtplib the module is used to enable or disable the debug option of the SMTP connection. It helps to view the data transmission between the SMTP server and the client.

Syntax

SMTP.set_debuglevel(level)

Level:

This is an integer value. The “0” means no debug output. 1 stands for basic debug information. 2 is providing more debug output.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *