python 發(fā)送qq郵件的示例
python自帶了兩個模塊smtplib和email用于發(fā)送郵件。smtplib模塊主要負責發(fā)送郵件,它對smtp協(xié)議進行了簡單的封裝。email模塊主要負責郵件的構(gòu)造。
email包下有三個模塊:MIMEText,MIMEImage,MIMEMultipart
發(fā)送純文本qq郵件import smtplibfrom email.header import Headerfrom email.mime.text import MIMETextsender = ’888888@qq.com’ # 發(fā)送使用的郵箱receivers = [’888888@qq.com’] # 收件人,可以是多個任意郵箱message = MIMEText(’這里是正文!’, ’plain’, ’utf-8’)message[’From’] = Header('發(fā)送者', ’utf-8’) # 發(fā)送者message[’To’] = Header('接收者', ’utf-8’) # 接收者subject = ’這里是主題!’message[’Subject’] = Header(subject, ’utf-8’)try: # qq郵箱服務(wù)器主機 # 常見其他郵箱對應(yīng)服務(wù)器: # qq:smtp.qq.com 登陸密碼:系統(tǒng)分配授權(quán)碼 # 163:stmp.163.com 登陸密碼:個人設(shè)置授權(quán)碼 # 126:smtp.126.com 登陸密碼:個人設(shè)置授權(quán)碼 # gmail:smtp.gmail.com 登陸密碼:郵箱登錄密碼 smtp = smtplib.SMTP_SSL(’smtp.qq.com’) # 登陸qq郵箱,密碼需要使用的是授權(quán)碼 smtp.login(sender, ’abcdefghijklmn’) smtp.sendmail(sender, receivers, message.as_string()) smtp.quit() print('郵件發(fā)送成功')except smtplib.SMTPException: print('Error: 無法發(fā)送郵件')
html = '''<html> <body> <h2> HTML </h2> <div style=’font-weight:bold’> 格式郵件 </div> </body> </html> ''' message = MIMEText(html,’html’, ’utf-8’)
html = '''<html> <body> <h2> HTML </h2> <div style=’font-weight:bold’> 格式郵件帶圖片 </div> <img src='cid:imageTest'> </body> </html> '''message = MIMEMultipart(’related’)messageAlter = MIMEMultipart(’alternative’)message.attach(messageAlter)messageAlter.attach(MIMEText(html, ’html’, ’utf-8’))# 指定圖片為當前目錄fp = open(’test.png’, ’rb’)messageImage = MIMEImage(fp.read())fp.close()# 定義圖片ID,和圖片中的ID對應(yīng)messageImage.add_header(’Content-ID’, ’<imageTest>’)message.attach(messageImage)
from email.mime.multipart import MIMEMultipartmessage = MIMEMultipart()message.attach(MIMEText(’這里一封帶附件的郵件!’, ’plain’, ’utf-8’))# 添加附件# 其他格式如png,rar,doc,xls等文件同理。attach = MIMEText(open(’test.txt’, ’rb’).read(), ’base64’, ’utf-8’)attach['Content-Type'] = ’application/octet-stream’attach['Content-Disposition'] = ’attachment; filename='test.txt'’message.attach(attach)
以上就是python 發(fā)送qq郵件的示例的詳細內(nèi)容,更多關(guān)于python 發(fā)送qq郵件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 基于javaweb+jsp實現(xiàn)學(xué)生宿舍管理系統(tǒng)2. 多級聯(lián)動下拉選擇框,動態(tài)獲取下一級3. ASP.NET MVC實現(xiàn)樹形導(dǎo)航菜單4. 如何封裝一個Ajax函數(shù)5. Java 接口和抽象類的區(qū)別詳解6. Laravel Eloquent ORM高級部分解析7. Django模板之基本的 for 循環(huán) 和 List內(nèi)容的顯示方式8. jsp response.sendRedirect()用法詳解9. Spring security 自定義過濾器實現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實例代碼)10. PHP擴展之URL編碼、解碼及解析——URLs
