4

I am attempting to send an email with Flask-Mail with a .txt file attachment. Thus far either I get an error or the email sends but the .txt. file is blank I've tried it two ways:

One way following the documentation:

with current_app.open_resource("sample.txt") as fp:
    msg.attach("sample.txt","text/plain", fp.read())

This leads to an Error:

TypeError: 'exceptions.IOError' object is not callable

I also tried it without the open_resource method:

 msg.attach("sample.txt","text/plain")
    mail.send(msg)

This led to the email sending but the .txt. attachment was blank.

Full try/except block below

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"

What am I missing in order for the attachment to be properly sent?

gevorg
  • 4,835
  • 4
  • 35
  • 52
mikey8989
  • 484
  • 5
  • 14
  • Your code looks fine, I assume you have a problem with your mail server configuration or `sample.txt` file location. – gevorg Jul 05 '16 at 08:26

1 Answers1

3

According to Flask-Mail documentation, this should perfectly do it:

with current_app.open_resource("sample.txt") as fp:
    msg.attach("sample.txt","text/plain", fp.read())
mail.send(msg)
  • Where current_app.open_resource("sample.txt") opens file with sample.txt location to read
  • And msg.attach("sample.txt","text/plain", fp.read()) attaches it using sample.txt as attachment name
  • Finally mail.send(msg) sends email

Make sure your sample.txt file location is correct and if it does not work, enable debugging by app.config['DEBUG'] = True and see what is the error.

gevorg
  • 4,835
  • 4
  • 35
  • 52
  • i tried the same method its not working. question link - https://stackoverflow.com/questions/46811429/text-attachment-sent-using-flask-mail-is-not-received – deepak murthy Oct 19 '17 at 10:56