Masahiro Okubo

FastAPIでメール送信

FastAPIでメール送信
# メール機能部分
import os
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from pydantic import BaseModel, EmailStr
from typing import List
from dotenv import load_dotenv, find_dotenv
from starlette.responses import JSONResponse

load_dotenv(find_dotenv())


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


conf = ConnectionConfig(
    MAIL_USERNAME=os.getenv("MAIL_USERNAME"),
    MAIL_PASSWORD=os.getenv("MAIL_PASSWORD"),
    MAIL_FROM=os.getenv("MAIL_FROM"),
    MAIL_PORT=587,
    MAIL_SERVER=os.getenv("MAIL_SERVER"),
    MAIL_TLS=True,
    MAIL_SSL=False,
    USE_CREDENTIALS=True
)

template = """
<p>Thanks for using Fastapi-mail</p> 
"""


async def verification(email: EmailSchema) -> JSONResponse:
    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)
    return JSONResponse(status_code=200, content={"message": "email has been sent"})


# メールを各所で送信
# backgroundのタスクとかで入れると良いかと
await mail.verification(EmailSchema(email=[user.email]))

参考記事

fastapi-mail

Buy Me A Coffee

関連記事

copyright© 2016-2021 Masahiro Okubo