article

Monday, February 20, 2023

Python FastAPI How to Send Email using SMTP - smtplib

Python FastAPI How to Send Email using SMTP - smtplib

Install Fastapi

https://github.com/tiangolo/fastapi

pip install fastapi
C:\fastAPI\sendemail>pip install fastapi
C:\fastAPI\sendemail>pip install "uvicorn[standard]"

Install sqlalchemy jinja2
https://pypi.org/project/Jinja2/
C:\fastAPI\sendemail>pip install Jinja2

Create main.py
sendemail/main.py
#sendemail/main.py
from fastapi import FastAPI, Request, Form

from starlette.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

import smtplib
from email.message import EmailMessage

templates = Jinja2Templates(directory="templates")

app = FastAPI()

app.mount("/static",StaticFiles(directory="static",html=True),name="static")

@app.get("/")
def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.post("/submit")
def submit(name : str = Form(),emailAddress:str=Form(),message:str=Form()):
    print(name)
    print(emailAddress)
    print(message)

    email_address = "cairocoders0711@gmail.com" # type Email
    email_password = "cairocodersednalan" # If you do not have a gmail apps password, create a new app with using generate password. Check your apps and passwords https://myaccount.google.com/apppasswords

    # create email
    msg = EmailMessage()
    msg['Subject'] = "Email subject"
    msg['From'] = email_address
    msg['To'] = "clydeymojica0130@gmail.com" # type Email
    msg.set_content(
       f"""\
    Name : {name}
    Email : {emailAddress}
    Message : {message}    
    """,
        
    )
    # send email
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(email_address, email_password)
        smtp.send_message(msg)

    return "email successfully sent"
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

endemail/templates/index.html
//sendemail/templates/index.html
{% extends "base.html" %}

{% block title %}Home Page{% endblock %}

{% block content %}
<div class="container py-4"><p><h3>Python FastAPI How to Send Email using SMTP - smtplib</h3></p>
    <form id="contactForm" action="/submit" method="post">
      <div class="mb-3">
        <label class="form-label" for="name">Name</label>
        <input class="form-control" name="name" id="name" type="text" placeholder="Name" />
      </div>

      <div class="mb-3">
        <label class="form-label" for="emailAddress">Email Address</label>
        <input class="form-control" name="emailAddress" id="emailAddress" type="email" placeholder="Email Address" />
      </div>
  
      <div class="mb-3">
        <label class="form-label" for="message">Message</label>
        <textarea class="form-control" name="message" id="message" type="text" placeholder="Message" style="height: 10rem;"></textarea>
      </div>
  
      <div class="d-grid">
        <button class="btn btn-primary btn-lg" type="submit">Submit</button>
      </div>
    </form>
  </div>
{% endblock %}
sendemail/templates/base.html
//sendemail/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="{{ url_for('static', path='/styles.css')}}"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<title>{% block title %} My Webpage {% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
run the FastAPI app

C:\fastAPI\sendmail>uvicorn main:app --reload
with uvicorn using the file_name:app_instance open the link on the browser http://127.0.0.1:8000/
http://127.0.0.1:8000/docs

Related Post