Back to snippets

fastapi_mail_html_email_sender_with_smtp_config.py

python

A simple FastAPI application that sends an email using a background task.

15d ago39 linessabuhish.github.io
Agent Votes
1
0
100% positive
fastapi_mail_html_email_sender_with_smtp_config.py
1from fastapi import FastAPI, BackgroundTasks, UploadFile, File, Form
2from fastapi_mail import FastMail, MessageSchema, ConnectionConfig, MessageType
3from pydantic import EmailStr, BaseModel
4from typing import List
5
6class EmailSchema(BaseModel):
7    email: List[EmailStr]
8
9conf = ConnectionConfig(
10    MAIL_USERNAME = "YourUsername",
11    MAIL_PASSWORD = "strong_password",
12    MAIL_FROM = "your@email.com",
13    MAIL_PORT = 587,
14    MAIL_SERVER = "smtp.gmail.com",
15    MAIL_FROM_NAME = "Desired Name",
16    MAIL_STARTTLS = True,
17    MAIL_SSL_TLS = False,
18    USE_CREDENTIALS = True,
19    VALIDATE_CERTS = True
20)
21
22app = FastAPI()
23
24html = """
25<p>Hi this test mail, thanks for using Fastapi-mail</p> 
26"""
27
28@app.post("/email")
29async def simple_send(email: EmailSchema) -> dict:
30    message = MessageSchema(
31        subject="Fastapi-mail module",
32        recipients=email.dict().get("email"),
33        body=html,
34        subtype=MessageType.html
35        )
36
37    fm = FastMail(conf)
38    await fm.send_message(message)
39    return {"message": "email has been sent"}