實際開發過程中使用到郵箱的概率很高,那么如何借助python使用qq郵箱發送郵件呢?
代碼很簡單,短短幾行代碼就可以實現這個功能。
使用到的模塊有smtplib和email這個兩個模塊,關於這兩個模塊的方法就不多說了。
我們先說說網上常用的使用這那兩個模塊發送郵件的方法
代碼如下:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def SendEmail(fromAdd, toAdd, subject, attachfile, htmlText):
strFrom = fromAdd;
strTo = toAdd;
msg =MIMEText(htmlText);
msg['Content-Type'] = 'Text/HTML';
msg['Subject'] = Header(subject,'gb2312');
msg['To'] = strTo;
msg['From'] = strFrom;
smtp = smtplib.SMTP('smtp.qq.com');
smtp.login('501257367@qq.com','password');
try:
smtp.sendmail(strFrom,strTo,msg.as_string());
finally:
smtp.close;
if __name__ == "__main__":
SendEmail("501257367@qq.com","501257367@qq.com","","hello","hello world");
運行結果:
smtplib.SMTPAuthenticationError: (530, 'Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28')
報錯,需要一個安全的連接,例如SSL,因此接下來我們會使用SSL的方式去登錄,但是在那之前,我們需要做一些准備,打開qq郵箱,點擊設置->
賬戶,找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務,開啟IMAP/SMTP服務,然后根據要求使用手機發送到指定號碼,獲取授權碼,
這個授權碼就是你接下來登錄要使用的密碼,配置完成,上代碼
import smtplib
from email.mime.text import MIMEText
_user = "你的qq郵箱"
_pwd = "你的授權碼"
_to = "xxx@163.com"
msg = MIMEText("Test")
msg["Subject"] = "don't panic"
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)
運行結果如下:
大功告成