天天看點

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, )
    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.