Python使用QQ郵箱傳送多收件人email
阿新 • • 發佈:2019-01-02
實際開發過程中使用到郵箱的概率很高,那麼如何藉助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.