3

.txt ファイルが添付された Flask-Mail でメールを送信しようとしています。これまでのところ、エラーが発生するか、メールが送信されますが.txt. ファイルは空白です。2 つの方法で試しました。

ドキュメントに従う1つの方法:

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"

添付ファイルを適切に送信するために不足しているものは何ですか?

4

1 に答える 1

3

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てエラーの原因を確認してください。

于 2016-07-05T08:25:28.203 に答える