为什么使用 Flask Mail 发送的文本附件是空的?
Why text attachment sent using Flask Mail is empty?
我正在尝试使用带有 .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/except 区块下方
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"
为了正确发送附件,我缺少什么?
根据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
启用调试并查看错误是什么。
我正在尝试使用带有 .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/except 区块下方
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"
为了正确发送附件,我缺少什么?
根据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
启用调试并查看错误是什么。