0

Traceback (most recent call last):
  File "E:\blahblahblah\emailsend.py", line 26, in <module>
    msg.attach(MIMEText(file))
  File "E:\blahblahblah\Python 2.7.11\lib\email\mime\text.py", line 30, in __init__
    self.set_payload(_text, _charset)
  File "E:\blahblahblah\Python 2.7.11\lib\email\message.py", line 226, in set_payload
    self.set_charset(charset)
  File "E:\blahblahblah\Python 2.7.11\lib\email\message.py", line 268, in set_charset
    cte(self)
  File "E:\blahblahblah\Python 2.7.11\lib\email\encoders.py", line 73, in encode_7or8bit
    orig.encode('ascii')
AttributeError: 'file' object has no attribute 'encode'https://stackoverflow.com/questions/ask#

I've been looking this up a lot but I haven't found an answer.

The only important parts of the code is this:

file = open('newfile.txt')

msg.attach(MIMEText(file))

There are other parts but I've debugged it and I get the error at the 'msg.attach(MIMEText(file))' line.

Any help?

9
  • Where did you read that MIMEText() can take a file? Commented Jun 15, 2016 at 18:05
  • @IgnacioVazquez-Abrams I thought the open() would convert it to a string inside the variable. Commented Jun 15, 2016 at 18:07
  • Where did you read that open() returns text? Commented Jun 15, 2016 at 18:07
  • open() returns a file object. docs.python.org/2/library/functions.html#open. In python 2 another name for open() is file(), which is why you should not have a variable named file. Commented Jun 15, 2016 at 18:08
  • @cdarke thank you for the link. I am relatively new to Python so I assumed it would open a .txt as a string. Commented Jun 15, 2016 at 18:10

1 Answer 1

4

MIMEText takes the content of the file, not the file object.

msg.attach(MIMEText(open("newfile.txt").read()))
Sign up to request clarification or add additional context in comments.

1 Comment

thanks it worked. You are missing another closing bracket though. It should be: msg.attach(MIMEText(open("newfile.txt").read()))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.