python 發(fā)送qq郵件的示例
更新時間:2021年03月15日 16:49:43 作者:可愛的黑精靈
這篇文章主要介紹了python 發(fā)送qq郵件的示例,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下
python自帶了兩個模塊smtplib和email用于發(fā)送郵件。smtplib模塊主要負責發(fā)送郵件,它對smtp協(xié)議進行了簡單的封裝。email模塊主要負責郵件的構造。
email包下有三個模塊:MIMEText,MIMEImage,MIMEMultipart
發(fā)送純文本qq郵件
import smtplib from email.header import Header from email.mime.text import MIMEText sender = '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郵箱服務器主機 # 常見其他郵箱對應服務器: # qq:smtp.qq.com 登陸密碼:系統(tǒng)分配授權碼 # 163:stmp.163.com 登陸密碼:個人設置授權碼 # 126:smtp.126.com 登陸密碼:個人設置授權碼 # gmail:smtp.gmail.com 登陸密碼:郵箱登錄密碼 smtp = smtplib.SMTP_SSL('smtp.qq.com') # 登陸qq郵箱,密碼需要使用的是授權碼 smtp.login(sender, 'abcdefghijklmn') smtp.sendmail(sender, receivers, message.as_string()) smtp.quit() print("郵件發(fā)送成功") except smtplib.SMTPException: print("Error: 無法發(fā)送郵件")
發(fā)送HTML格式郵件
html = """ <html> <body> <h2> HTML </h2> <div style='font-weight:bold'> 格式郵件 </div> </body> </html> """ message = MIMEText(html,'html', 'utf-8')
發(fā)送HTML格式郵件帶圖片
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對應 messageImage.add_header('Content-ID', '<imageTest>') message.attach(messageImage)
發(fā)送帶附件郵件
from email.mime.multipart import MIMEMultipart message = 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)容,更多關于python 發(fā)送qq郵件的資料請關注腳本之家其它相關文章!
相關文章
Python3讀取和寫入excel表格數(shù)據(jù)的示例代碼
這篇文章主要介紹了Python3讀取和寫入excel表格數(shù)據(jù)的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06基于Python+Pygame實現(xiàn)經(jīng)典賽車游戲
這篇文章主要為大家分享了一個基于Python和Pygame實現(xiàn)的賽車小游戲,文中的示例代碼講解詳細,對我們學習Python有一定幫助,需要的可以參考一下2022-04-04Python爬取OPGG上英雄聯(lián)盟英雄勝率及選取率信息的操作
這篇文章主要介紹了Python爬取OPGG上英雄聯(lián)盟英雄勝率及選取率信息的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04