关键点1:收件人邮箱msg_to=['[email protected]','[email protected]','[email protected]'],以列表的方式给出。
关键点2:msg['To'] =','.join(msg_to)。
关键点3:s.sendmail(msg_from, msg['To'].split(','), msg.as_string())至于join()和split()大家可以看文档明白含义用法,处理好这三个关键点就可以成功利用python发送邮件给多人了。
实例:
法一:
import smtplib
from email.mime.text import MIMEText
sender='[email protected]' #发送邮件的邮箱
pwd ='indqrfdfsdsvbxxx'# 发送方邮箱的授权码 码:Zhang1995 [email protected],[email protected],
receivers=['[email protected],[email protected]']#接收方的邮箱
message =MIMEText('我要群发给几个人','plain','utf-8')#第二个plain为设置文本格式
#设置发送已经接受邮件的邮件头部信息, 主题名
message['From']=sender
message['To']=','.join(receivers)
#邮件主题
subject='我是'
message['Subject']=Header(subject,'utf-8')
try:
#使用非本地服务器,需要建立ssl连接
# smtpObj = smtplib.SMTP_SSL('smtp.163.com',465)
smtpObj = smtplib.SMTP_SSL('smtp.qq.com',465)
# smtpObj= smtplib.SMTP('localhost')
smtpObj.login(sender,pwd)
smtpObj.sendmail(sender,message['To'].split(','),message.as_string())
print('邮件发送成功')
except smtplib.SMTPException as e:
print('ERROR:无法发送邮件.Case:%s'%e)
测试成功,俩人都可以收到邮件。