如何使用fastapi-mail库在FastAPI中发送带附件的电子邮件?

问题描述 投票:0回答:2
@app.post("/file")
async def send_file(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(...),
    email:EmailStr = Form(...)
    ) -> JSONResponse:

    message = MessageSchema(
            subject="Fastapi mail module",
            recipients=[email],
            body="Simple background task",
            subtype=MessageType.html,
            attachments=[file])

    fm = FastMail(conf)

    background_tasks.add_task(fm.send_message,message)

    return JSONResponse(status_code=200, content={"message": "email has been sent"}

上述代码取自fastapi-mail的文档页面。

要求

我没有文件,我有文件路径,我需要从中读取内容并需要发送文件(CSV、PDF...)。我怎样才能做到这一点?

@app.post("/file")
async def send_file(
    background_tasks: BackgroundTasks,
    file_path: str,
    email: EmailStr
) -> JSONResponse:
    message = MessageSchema(
        subject="Fastapi mail module",
        recipients=[email],
        body="Simple background task",
        subtype=MessageType.html,
        attachments=[file_path])

    )
    message.attach(file_data, filename="")
    fm = FastMail(conf)
    background_tasks.add_task(fm.send_message, message)
    return JSONResponse(status_code=200, content={"message": "email has been sent"})
python csv email fastapi email-attachments
2个回答
0
投票

attachments 数组是一个元组数组,例如 附件=[(“文件名”,“文件类型”,文件数据)]

其中 file_data 是打开文件中 file.read() 的结果,就像 Chris 所说的

这是一个例子:

@app.post("/file")
async def send_file(background_tasks: BackgroundTasks, file_path: str, email: EmailStr) -> JSONResponse:
    with open(file_path, 'rb') as f:
        file_data = f.read()

    message = MessageSchema(
        subject="Fastapi mail module",
        recipients=[email],
        body="Simple background task",
        subtype="html",
        attachments=[("filename", "filetype", file_data)]
    )

    fm = FastMail(conf)
    background_tasks.add_task(fm.send_message, message)

    return JSONResponse(status_code=200, content={"message": "email has been sent"})

0
投票
async def email(file_path:str):
    subject = ""
    content= ""
    message = MessageSchema(
        subject=subject,
        recipients=[],
        cc=[],
        body=content,
        subtype="html",
        attachments=[file_path],
    )
    fm = FastMail(conf)
    await fm.send_message(message)
    return {"success": True}

我可以直接将 file_path 传递为 str

as dict 需要通过打开来读取file

{“文件”:f“{file_path}”,“内容”:文件}

as UploadFile(未尝试)

回复:

附件位于 Outlook 项目内(需要工作),但它可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.