AttributeError:'file'对象没有属性'encode'

时间:2016-06-15 18:03:07

标签: python

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#

我一直在寻找这个,但我没有找到答案。

代码中唯一重要的部分是:

file = open('newfile.txt')

msg.attach(MIMEText(file))

还有其他部分,但我已调试它,我在'msg.attach(MIMEText(文件))'行收到错误。

任何帮助?

1 个答案:

答案 0 :(得分:2)

MIMEText获取文件的内容,而不是文件对象。

msg.attach(MIMEText(open("newfile.txt").read()))