經測試可用的發送郵件代碼:
import smtplib
from email.mime.text import MIMEText
# 第三方 SMTP 服務
mail_host = "smtp.163.com" # SMTP服務器
mail_user = "username" # 用戶名
mail_pass = "passwd" # 密碼(這里的密碼不是登錄郵箱密碼,而是授權碼)
sender = 'sender_mail@163.com' # 發件人郵箱
receivers = ['receive_mail@qq.com'] # 接收人郵箱
content = 'Python Send Mail !'
title = 'Python SMTP Mail Test' # 郵件主題
message = MIMEText(content, 'plain', 'utf-8') # 內容, 格式, 編碼
message['From'] = "{}".format(sender)
message['To'] = ",".join(receivers)
message['Subject'] = title
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 啟用SSL發信, 端口一般是465
smtpObj.login(mail_user, mail_pass) # 登錄驗證
smtpObj.sendmail(sender, receivers, message.as_string()) # 發送
print("mail has been send successfully.")
except smtplib.SMTPException as e:
print(e)
問題解決與注意點:
1.報錯:Error: A secure connection is requiered(such as ssl)
解決:因為郵箱SSL驗證的問題,因此把smtplib.SMTP()改成smtplib.SMTP_SSL(),端口號為465
2.報錯:535, b'Error: authentication failed'
解決:可能是由於用戶名不正確,因此代碼中的用戶名應該填寫為郵箱地址@前面部分 ,或是在郵箱設置的帳戶昵稱,如下圖昵稱Morning和馬賽克部分,都可作為用戶名
3.SMTP服務器可根據發送的郵箱做相應的選擇,如代碼中使用163郵箱則設為mail_host = "smtp.163.com"
可以改成"smtp.126.com"、"smtp.qq.com"等等
4.代碼中的密碼mail_pass為授權碼,並非郵箱密碼,授權碼用於登錄第三方郵件客戶端的專用密碼
QQ郵箱可通過設置→帳戶→生成授權碼;網易郵箱126/163可通過設置→客戶端授權密碼