python 發(fā)送qq郵件的示例
python自帶了兩個(gè)模塊smtplib和email用于發(fā)送郵件。smtplib模塊主要負(fù)責(zé)發(fā)送郵件,它對(duì)smtp協(xié)議進(jìn)行了簡(jiǎn)單的封裝。email模塊主要負(fù)責(zé)郵件的構(gòu)造。
email包下有三個(gè)模塊:MIMEText,MIMEImage,MIMEMultipart
發(fā)送純文本qq郵件import smtplibfrom email.header import Headerfrom email.mime.text import MIMETextsender = ’888888@qq.com’ # 發(fā)送使用的郵箱receivers = [’888888@qq.com’] # 收件人,可以是多個(gè)任意郵箱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ù)器主機(jī) # 常見其他郵箱對(duì)應(yīng)服務(wù)器: # qq:smtp.qq.com 登陸密碼:系統(tǒng)分配授權(quán)碼 # 163:stmp.163.com 登陸密碼:個(gè)人設(shè)置授權(quán)碼 # 126:smtp.126.com 登陸密碼:個(gè)人設(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’))# 指定圖片為當(dāng)前目錄fp = open(’test.png’, ’rb’)messageImage = MIMEImage(fp.read())fp.close()# 定義圖片ID,和圖片中的ID對(duì)應(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郵件的示例的詳細(xì)內(nèi)容,更多關(guān)于python 發(fā)送qq郵件的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. JS sort方法基于數(shù)組對(duì)象屬性值排序2. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式3. JAVA上加密算法的實(shí)現(xiàn)用例4. 基于javascript處理二進(jìn)制圖片流過程詳解5. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)6. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟7. idea開啟代碼提示功能的方法步驟8. Java Lock接口實(shí)現(xiàn)原理及實(shí)例解析9. Django-migrate報(bào)錯(cuò)問題解決方案10. ajax請(qǐng)求添加自定義header參數(shù)代碼
