Python使用QQ郵箱發(fā)送Email的方法實例
前言
其實Python使用QQ郵箱發(fā)送Email代碼很簡單,短短幾行代碼就可以實現(xiàn)這個功能。
使用到的模塊有smtplib和email這個兩個模塊,關于這兩個模塊的方法就不多說了。不了解的朋友們可以查看這篇文章:python中使用smtplib和email模塊發(fā)送郵件實例
我們先說說網(wǎng)上常用的使用這那兩個模塊發(fā)送郵件的方法
代碼如下:
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服務,然后根據(jù)要求使用手機發(fā)送到指定號碼,獲取授權碼,
這個授權碼就是你接下來登錄要使用的密碼,配置完成,上代碼
import smtplib from email.mime.text import MIMEText _user = "你的qq郵箱" _pwd = "你的授權碼" _to = "501257367@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
運行結果如下:
總結
好了,大功告成!以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家學習或者使用python能帶來一定的幫助,如果有疑問大家可以留言交流。
相關文章
python 實現(xiàn)快速生成連續(xù)、隨機字母列表
今天小編就為大家分享一篇python 實現(xiàn)快速生成連續(xù)、隨機字母列表,具有很好的價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11Python實現(xiàn)城市公交網(wǎng)絡分析與可視化
這篇文章主要介紹了通過Python爬取城市公交站點、線路及其經(jīng)緯度數(shù)據(jù),并做可視化數(shù)據(jù)分析。文中的示例代碼講解詳細,感興趣的可以學習一下2021-12-12在Python中調(diào)用Ping命令,批量IP的方法
今天小編就為大家分享一篇在Python中調(diào)用Ping命令,批量IP的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01