1.發送QQ郵件,首先必須知道QQ郵箱的SMTP服務器
http://service.mail.qq.com/cgi-bin/help?id=28&no=167&subtype=1
2.發送郵件之前,必須開啟qq郵箱的smtp服務
設置路徑:郵箱設置--賬戶--開啟截圖服務--保存更改
3.代碼拋出異常分析
(1)郵箱密碼傳入值為日常登錄密碼,報錯
global send_userglobal email_hostglobal passwordpassword = 'xxx92'email_host = "smtp.qq.com"send_user = "[email protected]"
拋出異常:
smtplib.SMTPAuthenticationError:(535, b'Error: \\xc7\\xeb\\xca\\xb9\\xd3\\xc3\\xca\\xda\\xc8\\xa8\\xc2\\xeb\\xb5\\xc7\\xc2\\xbc\\xa1\\xa3\\xcf\\xea\\xc7\\xe9\\xc7\\xeb\\xbf\\xb4: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256')
http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
修改代碼:
(2)安全郵件,需要通過SSL發送
server = smtplib.SMTP()server.connect(email_host,25)
拋出異常:
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
QQ郵箱是支持安全郵件的,需要通過SSL發送的郵件:使用標準的25端口連接SMTP服務器時,使用的是明文傳輸,發送郵件的整個過程可能會被竊聽。要更安全地發送郵件,可以加密SMTP會話,實際上就是先創建SSL安全連接,然後再使用SMTP協議發送郵件
修改代碼:
server = smtplib.SMTP_SSL()server.connect(email_host,465)# 啟用SSL發信, 端口一般是465
4.附上完整代碼
#coding:utf-8import smtplibfrom email.mime.text import MIMETextclass SendEmail: global send_user global email_host global password password = "lunkbrgwqxhfjgxx" email_host = "smtp.qq.com" send_user = "[email protected]" def send_mail(self,user_list,sub,content): user = "shape" + "" message = MIMEText(content,_subtype='plain',_charset='utf-8') message['Subject'] = sub message['From'] = user message['To'] = ";".join(user_list) server = smtplib.SMTP_SSL() server.connect(email_host,465) server.login(send_user,password) server.sendmail(user,user_list,message.as_string()) server.close()if __name__ == '__main__': send = SendEmail() user_list = ['[email protected]'] sub = "測試郵件" content = "ceshi看看" send.send_mail(user_list,sub,content)
(1)Python對SMTP支持有smtplib和email兩個模塊,email負責構造郵件,smtplib負責發送郵件
(2)構造MIMEText對象時,第一個參數是郵件正文;第二個參數是MIME的subtype,傳入'plain'表示純文本,最終的MIME就是'text/plain';最後一定要用utf-8編碼保證多語言兼容性
(3)發送的郵件需要添加頭部信息,頭部信息中包含發送者、接收者、郵件主題等信息:message['From']、message['To']、message['Subject']
(4)構造完要發送的郵件信息後,通過SMTP發出去:login()方法用來登錄SMTP服務器;sendmail()方法就是發郵件,由於可以一次發給多個人,所以傳入一個list;郵件正文是一個str,as_string()把MIMEText對象變成str
(5)SMTP.close() :關閉SMTP服務器連接
閱讀更多 繁華落盡and曲終人散 的文章