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  = ['[email protected]','[email protected]']     #接收邮件列表,是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.

你可能感兴趣的:(Python应用,python,qq邮箱,电子邮件,邮箱,邮件)