3

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

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

4

1 回答 1

3

根据Flask-Mail 文档,这应该完美地做到这一点:

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并查看错误。

于 2016-07-05T08:25:28.203 回答