我正在尝试使用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'
答案 0 :(得分:0)
来自@shaktimaan评论
您的附件已经是MIMEText对象。那么,为什么还要在mag.attach()中再次这样做呢?您是否尝试过msg.attach(attachment)?