python - 属性错误 : MIMEText instance has no attribute 'encode'

标签 python

我正在尝试使用 smtplib 发送附件。但由于某些原因,我得到了这个回溯。任何帮助将非常感激。

#!/usr/bin/python

import smtplib
import getpass
from email import Encoders
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

fromaddr = "<email>"
toaddr = "<email>"

username = "email"
password = getpass.getpass("Email password : ")
filename = 'test.txt'
f = file(filename)
msg = MIMEMultipart()
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition','attachment',filename = filename)
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = 'Test'
msg.attach(MIMEText(attachment))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr,toaddr,msg.as_string())
server.quit()

错误:
Traceback (most recent call last):
  File "./emailte.py", line 21, in <module>
    msg.attach(MIMEText(attachment))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/email/mime/text.py", line 30, in __init__
    self.set_payload(_text, _charset)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/email/message.py", line 226, in set_payload
    self.set_charset(charset)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/email/message.py", line 268, in set_charset
    cte(self)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/email/encoders.py", line 73, in encode_7or8bit
    orig.encode('ascii')
AttributeError: MIMEText instance has no attribute 'encode'

最佳答案

来自@shaktimaan 评论

Your attachment is already a MIMEText object. So, why do that again in mag.attach()? Have you tried msg.attach(attachment)?

关于python - 属性错误 : MIMEText instance has no attribute 'encode' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25706976/

相关文章:

python - 使用 Python Tk 作为线程代码的前端

python - 对 Learn Python the Hard Way ex43 中的类感到困惑?

python - pandas 是否可以在 diff 操作中将(NULL)不存在的索引/值视为 0?

Python MemoryError - 是否有更有效的方法来处理我巨大的 CSV 文件?

python - 为 Django View 实现 HTTP Digest Auth

python - 使用 NetworkX 查找从一个到另一个的最短和最长权重

python - Scipy 插值.splprep 错误 "Invalid Inputs"

python - 无法使用 Selenium Webdriver 运行 Firefox

python - 将新的 "git ..."子命令实现为 Python 脚本

python - 如何使用Python在excel上打印开始时间和结束时间?