我正在尝试使用带有.txt文件附件的Flask-Mail发送电子邮件。到目前为止,我收到错误或电子邮件发送但.txt。文件是空白我已经尝试过两种方式:
遵循文档的一种方式:
with current_app.open_resource("sample.txt") as fp:
msg.attach("sample.txt","text/plain", fp.read())
这会导致错误:
TypeError: 'exceptions.IOError' object is not callable
我也尝试过没有open_resource方法:
msg.attach("sample.txt","text/plain")
mail.send(msg)
这导致了电子邮件发送但是.txt。附件是空白的。
下面的完整尝试/除外块
try:
msg = Message("New File",
sender="SENDER",
recipients=["RECIPIENT"])
msg.body = "Hello Flask message sent from Flask-Mail"
with current_app.open_resource("sample.txt") as fp:
msg.attach("sample.txt","text/plain", fp.read())
mail.send(msg)
except Exception as e:
return e
return "file was successfully sent"
为了正确发送附件,我缺少什么?
答案 0 :(得分:1)
根据Flask-Mail documentation,这应该是完美的:
with current_app.open_resource("sample.txt") as fp:
msg.attach("sample.txt","text/plain", fp.read())
mail.send(msg)
current_app.open_resource("sample.txt")
打开sample.txt
位置的文件以供阅读msg.attach("sample.txt","text/plain", fp.read())
使用sample.txt
作为附件名称mail.send(msg)
发送电子邮件确保您的sample.txt
文件位置正确,如果它不起作用,请按app.config['DEBUG'] = True
启用调试,看看错误是什么。