在使用騰訊企業郵箱發送郵件時出現報錯:AttributeError: 'list' object has no attribute 'encode'
原因:收件人不能用列表存儲數據,需要轉為字符串,以逗號分割
解決方法:
將收件人列表轉為字符串,以逗號分割
to_list = ['a@xx.com', 'b@xx.com'] msg['to'] = ','.join(to_list)
完整代碼:
import smtplib from email.mime.text import MIMEText from email.header import Header name = 'xx@xxx.cn' pwd = 'xxx' to_list = ['xx@xxx.cn'] content = '<html><head><title>test</title></head><body>這是測試郵件內容</body></html>' msg = MIMEText(content, 'html', 'utf-8') msg['form'] = Header('huyang', 'utf-8') msg['to'] = ','.join(to_list) # 重點是這個位置 msg['subject'] = Header('測試郵件', 'utf-8') #---發送 smtp = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465) smtp.login(name, pwd) smtp.sendmail(name, to_list, msg.as_string()) print('發送成功!')