前言
其實(shí)Python使用QQ郵箱發(fā)送Email代碼很簡(jiǎn)單,短短幾行代碼就可以實(shí)現(xiàn)這個(gè)功能。
使用到的模塊有smtplib和email這個(gè)兩個(gè)模塊,關(guān)于這兩個(gè)模塊的方法就不多說(shuō)了。不了解的朋友們可以查看這篇文章:python中使用smtplib和email模塊發(fā)送郵件實(shí)例
我們先說(shuō)說(shuō)網(wǎng)上常用的使用這那兩個(gè)模塊發(fā)送郵件的方法
代碼如下:
import smtplibfrom email.mime.text import MIMETextfrom email.header import Headerdef 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");運(yùn)行結(jié)果:
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')
報(bào)錯(cuò),需要一個(gè)安全的連接,例如SSL,因此接下來(lái)我們會(huì)使用SSL的方式去登錄,但是在那之前,我們需要做一些準(zhǔn)備,打開(kāi)qq郵箱,點(diǎn)擊設(shè)置->
賬戶,找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務(wù),開(kāi)啟IMAP/SMTP服務(wù),然后根據(jù)要求使用手機(jī)發(fā)送到指定號(hào)碼,獲取授權(quán)碼,
這個(gè)授權(quán)碼就是你接下來(lái)登錄要使用的密碼,配置完成,上代碼
import smtplibfrom email.mime.text import MIMEText_user = "你的qq郵箱"_pwd = "你的授權(quán)碼"_to = "501257367@163.com"msg = MIMEText("Test")msg["Subject"] = "don't panic"msg["From"] = _usermsg["To"] = _totry: 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 運(yùn)行結(jié)果如下:

總結(jié)
好了,大功告成!以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家學(xué)習(xí)或者使用python能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流。
新聞熱點(diǎn)
疑難解答
圖片精選