Python使用QQ邮箱发送多收件人email

实际开发过程中使用到邮箱的概率很高,那么如何借助python使用qq邮箱发送邮件呢?
代码很简单,短短几行代码就可以实现这个功能。

使用到的模块有smtplib和email这个两个模块,关于这两个模块的方法就不多说了。
代码如下:

#coding:utf-8 # 强制使用utf-8编码格式

# 加载smtplib模块
import smtplib
from email.mime.text import MIMEText
import string

#第三方SMTP服务
mail_host = "smtp.qq.com"           # 设置服务器
mail_user = "572****@qq.com"        # 用户名
mail_pwd  = "***********"      # 口令,QQ邮箱是输入授权码,在qq邮箱设置 里用验证过的手机发送短信获得,不含空格
mail_to  = ['12345678@qq.com','8888888@qq.com']     #接收邮件列表,是list,不是字符串


#邮件内容
msg = MIMEText("尊敬的用户:您的注册申请已被接受。您可以尝试点击下面的连接进行激活操作。")      # 邮件正文
msg['Subject'] = "A test email for python !"     # 邮件标题
msg['From'] = mail_user        # 发件人
msg['To'] = ','.join(mail_to)         # 收件人,必须是一个字符串

try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)
    smtpObj.login(mail_user, mail_pwd)
    smtpObj.sendmail(mail_user,mail_to, msg.as_string())
    smtpObj.quit()
    print("邮件发送成功!")
except smtplib.SMTPException:
    print ("邮件发送失败!")

细心的读者会发现代码中有这样一句:msg[‘to’]=’,’.join(strTo),但是msg[[‘to’]并没有在后面被使用,这么写明显是不合理的,但是这就是stmplib的bug。你只有这样写才能群发邮件。

The problem is that SMTP.sendmail and email.MIMEText need two different things.

email.MIMEText sets up the “To:” header for the body of the e-mail. It is ONLY used for displaying a result to the
 human beingat the other end, and like all e-mail headers, must be a single string. (Note that it does not
 actually have to have anything to do with the people who actually receive the message.)

SMTP.sendmail, on the other hand, sets up the “envelope” of the message for the SMTP protocol. It needs a Python
 list of string, each of which has a single address.

So, what you need to do is COMBINE the two replies you received. Set msg‘To’ to a single string, but pass the raw
 list to sendmail.
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值