为什么使用Flask Mail发送的文本附件为空?

时间:2016-06-04 23:53:36

标签: python email flask flask-mail

我正在尝试使用带有.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"

为了正确发送附件,我缺少什么?

1 个答案:

答案 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启用调试,看看错误是什么。