📜  在Python中使用 FastAPI 框架发送电子邮件(1)

📅  最后修改于: 2023-12-03 15:37:37.529000             🧑  作者: Mango

在Python中使用 FastAPI 框架发送电子邮件

在应用程序开发中,电子邮件通常是必要的一部分,用于发送验证码,通知和其他信息。 在Python中,可以使用FastAPI框架来创建一个快速且易于使用的电子邮件发送功能,本篇介绍如何使用FastAPI框架来发送电子邮件。

步骤一: 安装FastAPI和其依赖项
!pip install fastapi[all]
!pip install uvicorn[standard]
步骤二: 导入必要的模块
from fastapi import FastAPI, Depends
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from typing import List
from pydantic import EmailStr
步骤三: 配置电子邮件发送功能
conf = ConnectionConfig(
    MAIL_USERNAME = "your_mail_username",
    MAIL_PASSWORD = "your_mail_password",
    MAIL_FROM = "your_mail_address",
    MAIL_PORT = 587,
    MAIL_SERVER = "smtp.gmail.com",
    MAIL_TLS = True,
    MAIL_SSL = False,
    USE_CREDENTIALS = True
)

fast_mail = FastMail(conf)
步骤四: 创建发送邮件的函数
async def send_email(to: List[EmailStr], subject: str, body: str):
    message = MessageSchema(
        subject=subject,
        recipients=to,
        body=body,
        subtype="html"
    )
    response = await fast_mail.send_message(message)
    return {"message": "email has been sent", "response": response}
步骤五: 在FastAPI中使用发送邮件的函数
app = FastAPI()

@app.post("/send_email")
async def send(to: List[EmailStr], subject: str, body: str):
    return await send_email(to, subject, body)

现在,您已经可以在FastAPI应用程序中使用上述代码来发送电子邮件。 以下是完整的代码:

from fastapi import FastAPI, Depends
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from typing import List
from pydantic import EmailStr

conf = ConnectionConfig(
    MAIL_USERNAME = "your_mail_username",
    MAIL_PASSWORD = "your_mail_password",
    MAIL_FROM = "your_mail_address",
    MAIL_PORT = 587,
    MAIL_SERVER = "smtp.gmail.com",
    MAIL_TLS = True,
    MAIL_SSL = False,
    USE_CREDENTIALS = True
)

fast_mail = FastMail(conf)

async def send_email(to: List[EmailStr], subject: str, body: str):
    message = MessageSchema(
        subject=subject,
        recipients=to,
        body=body,
        subtype="html"
    )
    response = await fast_mail.send_message(message)
    return {"message": "email has been sent", "response": response}

app = FastAPI()

@app.post("/send_email")
async def send(to: List[EmailStr], subject: str, body: str):
    return await send_email(to, subject, body)

以上就是如何使用FastAPI框架来发送电子邮件的完整过程。 现在,您可以继续在应用程序中使用这个功能来发送任何电子邮件,例如密码重置邮件,账号确认邮件等。