gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:39:49 26 4
gpt4 key购买 nike

我正在尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com