【Python3】 发送邮件给多人

 

1、收件人邮箱msg_to=['[email protected],[email protected],[email protected]'],以列表的方式给出。
2、message['To'] =','.join(msg_to)
3、s.sendmail(sender, message['To'].split(','), sender.as_string())

至于join()和split()大家可以看文档明白含义用法,处理好这三个关键点就可以成功利用Python发送邮件给多人了。

import smtplib
from email.header import Header  # 用来设置邮件头和邮件主题
from email.mime.text import MIMEText  # 发送正文只包含简单文本的邮件,引入MIMEText即可

# 发件人和收件人
sender = '[email protected]'

# 所使用的用来发送邮件的SMTP服务器
smtpServer = 'smtp.163.com'

# 发送邮箱的用户名和授权码(不是登录邮箱的密码)
username = '[email protected]'
password = 'Jianzhong0513'

mail_title = '【建众帮】iOS测试版本'
mail_body = '赶紧下载体验吧! http://www.pgyer.com/Z8MH'

msg_to = ['[email protected],[email protected],[email protected]']

# 创建一个实例
message = MIMEText(mail_body, 'plain', 'utf-8')  # 邮件正文
message['From'] = sender  # 邮件上显示的发件人
message['To'] = ','.join(msg_to)  # 邮件上显示的收件人
message['Subject'] = Header(mail_title, 'utf-8')  # 邮件主题

try:
    smtp = smtplib.SMTP()  # 创建一个连接
    smtp.connect(smtpServer)  # 连接发送邮件的服务器
    smtp.login(username, password)  # 登录服务器
    smtp.sendmail(sender, message['To'].split(','), message.as_string())  # 填入邮件的相关信息并发送
    print("邮件发送成功!!!")
    smtp.quit()
except smtplib.SMTPException:
    print("邮件发送失败")

你可能感兴趣的:(【Python3】 发送邮件给多人)