将自定义附件(带有 StringIO 的内存文件)添加到 fastapi-mail

Adding a custom attachment (In-memory file with StringIO) to fastapi-mail

我是 fastapi(通常 python)的新手,我正在努力使用 fastapi-mail 发送内存中的文件作为附件。

我正在使用字符串 IO 在内存中写入 CSV 文件,如下所示:

file: io.StringIO = io.StringIO()
writer = csv.writer(file, delimiter=';')
writer.writerow(['name', 'area', 'country_code2', 'country_code3'])
writer.writerow(['Afghanistan', 652090, 'AF', 'AFG'])

并尝试像这样发送:

my_attachment = StreamingResponse(file.getvalue(), media_type="text/csv", headers={'Content-Disposition': 'attachment; filename=daily_stats.csv'})
message = MessageSchema(
    subject="my subject",
    recipients=["mail@mail.mail"],
    body="not working",
    subtype="text",
    attachments=[my_attachment]
)

fm = FastMail(myconf) # ConnectionConfig specified elsewhere
await fm.send_message(message)

但它正在爆炸并出现此错误:

File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init_
pydantic.error_wrappers.ValidationError: 3 validation errors for MessageSchema
attachments -> 0
   instance of UploadFile expected (type=type_error.arbitrary_type; expected_arbitrary_type=UploadFile)
attachments -> 0
   value is not a valid dict (type=type_error.dict)
attachments -> 0
   str type expected (type=type_error.str)

它在其他一些 smtp 客户端(例如 Python csv.writer - is it possible to write to a variable?)中似乎相对简单,但我坚持使用快速 api 一个

好的,所以我设法弄明白了...解决方案实际上非常简单,但由于 UploadFile 的文档非常有限,部分是猜测。

无论如何,创建文件后:

file: io.StringIO = io.StringIO()
writer = csv.writer(file, delimiter=';')
writer.writerow(['name', 'area', 'country_code2', 'country_code3'])
writer.writerow(['Afghanistan', 652090, 'AF', 'AFG'])

我只需要根据 io.StringIO 创建自己的 UploadFile 实例并传递它。当然必须确保 'rewind' 文件开始:

file.seek(0);
upload_file = UploadFile(filename="myfile", file=file, content_type="text/csv");
message = MessageSchema(
    subject="my subject",
    recipients=["mail@mail.mail"],
    body="not working",
    subtype="html",
    attachments=[upload_file]
    )

fm = FastMail(conf)
await fm.send_message(message)

就是这样..希望其他人觉得这有用