Python Code: 利用QQ郵箱發送郵件,解決SMTPAuthenticationError:530錯誤

本博客需要利用Python代碼給自己的QQ郵箱發送自定義郵件,其進階版就是要在服務器端把進程的錯誤信息實時轉發給QQ郵箱,實現遠程的操控。

一、原始版代碼:

# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText

SMTPserver = 'smtp.qq.com'
sender = 'sender's QQ [email protected]'
password = "sender's password"

message = 'I send a message by Python. 你好'
msg = MIMEText(message)

msg['Subject'] = 'Test Email by Python'
msg['From'] = sender
msg['To'] = 'receiver's QQ [email protected]'

mailserver = smtplib.SMTP(SMTPserver, 25)
mailserver.login(sender, password)
mailserver.sendmail(sender, [sender], msg.as_string())
mailserver.quit()
print 'send email success'
二、遇到錯誤:
顯示錯誤SMTPAuthenticationError:530,仔細看後面解釋:很明顯,是因爲QQ郵箱SSL驗證的問題,這是出於一種安全協議,所以我們的代碼也需要加上SSL這個裝備:
解決:
打開QQ郵箱--設置--賬戶--IMP/SMTP開啓--手機驗證--獲取pwd碼
三、進階版代碼:
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
_user = "sender's QQ [email protected]"
_pwd  = "your pwd password"
_to   = "receiver's QQ [email protected]"

msg = MIMEText("Test")
msg["Subject"] = "My Email From Myself!"
msg["From"]    = _user
msg["To"]      = _to

try:
    s = smtplib.SMTP_SSL("smtp.qq.com", 465)
    s.login(_user, _pwd)
    s.sendmail(_user, _to, msg.as_string())
    s.quit()
    print "Success!"
except smtplib.SMTPException,e:
    print "Falied,%s"%e
四、發送成功:

五、更多提示:
代碼裏面的:SMTPserver是SMTP郵件服務器SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協議,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。SMTP協議屬於TCP/IP協議族,它幫助每臺計算機在發送或中轉信件時找到下一個目的地。通過SMTP協議所指定的服務器,就可以把E-mail寄到收信人的服務器上了,整個過程只要幾分鐘。SMTP服務器則是遵循SMTP協議的發送郵件服務器,用來發送或中轉發出的電子郵件。
所以:裏面的:"smtp.qq.com"還可以改成“smtp.126.com”、"smtp.163.com"等等,根據sender的郵箱歸屬來定義。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章