使用QQ郵箱發送email(Python)


實際開發過程中使用到郵箱的概率很高,那么如何借助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) 

運行結果如下:

大功告成

上述是在Python2.7版本下完成的測試


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM