![](/img/trans.png)
[英]Python AttributeError: 'tuple' object has no attribute 'encode' in hashlib.encode
[英]AttributeError: 'tuple' object has no attribute 'encode' python
我编写了一个程序,使用 python smtp 库发送带有结果的电子邮件:
def send_mail(sender_mail, receiver_mail):
msg = MIMEMultipart()
msg['From'] = sender_mail
msg['To'] = receiver_mail
msg['Subject'] = "Test results"
file = open(RESULTS_FILE, "r")
# body = file.read()
##attachment = MIMEText(file.read())
attachment = MIMEBase('application', "octet-stream")
attachment.set_payload(file.read())
file.close()
attachment.add_header('Content-Disposition', 'attachment',
filename=RESULTS_FILE)
msg.attach(attachment)
body = "Attached the test results"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP("172.16.100.9", 25)
#server.starttls()
#server.login(sender_mail, password)
text = msg.as_string()
server.sendmail(sender_mail, receiver_mail, text)
server.quit()
但是当我尝试运行它时,似乎该行: text = msg.as_string()
导致错误:
Traceback (most recent call last):
File "\\filer2\incam\test_scripts\run_only_ci.py", line 268, in <module>
testresults.analyze_tests(TESTS_FOLDER, RESULTS_FOLDER, sender_mail, receiver_mail)
File "\\filer2\incam\test_scripts\testresults.py", line 224, in analyze_tests
send_mail(sender_mail, receiver_mail)
File "\\filer2\incam\test_scripts\testresults.py", line 119, in send_mail
text = msg.as_string()
File "C:\Users\fl_ncc\AppData\Local\Programs\Python\Python36\lib\email\message.py", line 158, in as_string
g.flatten(self, unixfrom=unixfrom)
File "C:\Users\fl_ncc\AppData\Local\Programs\Python\Python36\lib\email\generator.py", line 116, in flatten
self._write(msg)
File "C:\Users\fl_ncc\AppData\Local\Programs\Python\Python36\lib\email\generator.py", line 195, in _write
self._write_headers(msg)
File "C:\Users\fl_ncc\AppData\Local\Programs\Python\Python36\lib\email\generator.py", line 222, in _write_headers
self.write(self.policy.fold(h, v))
File "C:\Users\fl_ncc\AppData\Local\Programs\Python\Python36\lib\email\_policybase.py", line 326, in fold
return self._fold(name, value, sanitize=True)
File "C:\Users\fl_ncc\AppData\Local\Programs\Python\Python36\lib\email\_policybase.py", line 369, in _fold
parts.append(h.encode(linesep=self.linesep, maxlinelen=maxlinelen))
AttributeError: 'tuple' object has no attribute 'encode'
为什么会发生? 它以前有效,所以我不明白为什么会发生。 谢谢你的帮助。
注意你在send_mail函数中的代码“msg['To'] = receiver_mail”,这是没有必要的,因为sendmail有一个像flow一样的receiver_mail的参数。换句话说,你不必在msg['To'中强调receiver_mail ], msg['To'] 只显示邮件中的收件人信息。
server.sendmail(sender_mail, receiver_mail, text)
当 msg['To'] 被分配给像 ['XXX@XXX','XXX@XXX'] 这样的列表时会发生错误。如果你用像 "msg['To']='XXX@XXX' 这样的单个字符串来设置它“, 一切都会安好的。 然后,当接收者邮件的元素数 >1 时,您可以使用“for 循环”语句。 您还可以注释相关代码,如流动,以避免“for 循环”语句:
# msg['To'] = receiver_mail
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.