Python列表形式群发邮件之错误 ——AttributeError: ‘list’ object has no attribute ‘decode’

  • Post author:
  • Post category:python

python群发邮件的代码——收件邮箱是列表形式

## 导入 smtplib发送模块和email创建模块
import smtplib
from email.mime.text import MIMEText   # 发送邮件内容为文本形式时导入
from email.header import Header   #给邮件设置标题时导入

username = '239*******@qq.com'
password = input('请输入邮箱授权码:')
from_addr = username

## 1、设置列表形式的变量
to_addr = ['**********@136.com','127*******@qq.com','129*******@qq.com']

server_host = 'smtp.qq.com'
port = 25

text = "这是一封测试邮件,无需回复!"
msg = MIMEText(text,'plain','utf-8')
subject = 'Python email group sending test!'
msg['Subject'] = Header(subject,'utf-8')
msg['From'] = Header(from_addr)
msg['To'] = Header(to_addr)

server = smtplib.SMTP(server_host)
server.connect(server_host,port)
server.login(username, password)
try:
    server.sendmail(from_addr,to_addr,msg.as_string())
    print('Successfully!')
except:
    print('Failed!')
server.quit()

运行后出现的主要报错信息:

AttributeError: 'list' object has no attribute 'decode'

这是因为 Header 接收的第一个参数的类型只能是字符串或者字节
Header官方描述所示:在这里插入图片描述
解决方式:
使用 join() 函数,将列表中字符串使用某种字符串连接,形式——str.join(list) ,示例:

a = ['abc','123','xyz789']
b = ','
c =b.join(a)
print(c)
print(type(c)

运行结果

abc,123,xyz789
<class 'str'>

由此,可以将代码作以下修改

msg['To'] = Header(to_addr)

改成:

msg['To'] = Header(','.join(to_addr)) 

此时再次运行就顺利啦~

Successfully!
Process finished with exit code 0

版权声明:本文为weixin_42422090原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。