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

drkbr07n  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(198)
@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"})
vwhgwdsa

vwhgwdsa1#

attachments数组是一个元组数组,如attachments=[(“filename”,“filetype”,file_data)]
其中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"})
2vuwiymt

2vuwiymt2#

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传递

因为dict需要通过打开读取文件,并像这样传递。

attachments=[{“file”:f”{file_path}",“content”:文件}]


as**未尝试)

回复:

附件内的outlook项目(需要工作),但其工作.

相关问题