Python-自動傳送各種型別附件的郵件
阿新 • • 發佈:2021-12-08
傳送郵件的基本思路就是使用MIMEMultipart來組裝(attach)各個部分:郵件主題,郵件傳送者,郵件接收者,郵件正文以及附件等等,其中附件需要add_header加入附件宣告
繼承關係如下:
MIMEBase
--MIMENonMultipart
--MIMEApplication
--MIMEAudio
--MIMEImage
--MIMEMessage
--MIMEText
--MIMEMultipart
一般來說,不會直接使用到MIMEBase類,而是直接使用它的繼承類。MIMEMultipart有attach方法,而MIMENonMultipart沒有,只能被attach,MIME有很多種型別,而最終只提供(音訊: MIMEAudio;圖片: MIMEImage; 文字:MIMEText),如果是其它型別,如word,excel,html就不知道該用哪種型別
作者的附件型別是HTML,使用MIMIText一直不盡如人意,如下圖:
針對以上問題解決方案:
不管什麼型別的附件,都用MIMEApplication,它的預設子型別是application/octet-stream(二進位制檔案),客戶端比如qq郵箱,收到這個聲明後,會根據副檔名來猜測
貼作者程式碼:
#coding: utf-8 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header from email.mime.application import MIMEApplication import time from project_prctice.common import dir_config as Dir import os from project_prctice.common.logger import FrameLog as log class SendMail: def __init__(self): self.file = self.find_newest_file() def find_newest_file(self): ''' 查詢目錄下最新的檔案 :return: ''' file_list = os.listdir(Dir.reports_dir) file_list.sort() filepath = os.path.join(Dir.reports_dir, file_list[-2]) #因該資料夾下有__init__檔案,因此為固定輸出結果 return filepath def send_mail_html(self): ''' 傳送html內容郵件 :param file: :return: ''' msg = MIMEMultipart() #郵箱伺服器 smtpserver = "smtp.qq.com" #傳送郵箱地址 msg_from = "****@qq.com" # 傳送方郵箱授權碼 password = "rdtghsmihar" #接收郵箱 msg_to= "****@qq.com" #傳送郵件主題 t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) subject = "自動化測試報告_" + t #主題 content = "系統自動發出郵件,請勿回覆" #郵件正文內容 msg.attach(MIMEText(content, 'plain', 'utf-8')) #例項化一個MIMEText郵件物件,該物件需要寫進三個引數,分別是郵件正文,文字格式和編碼 msg['Subject'] = Header(subject,'utf-8') msg['From'] = msg_from msg['To'] = msg_to #---這是附件部分----- #xlsx型別附件 # attachment = MIMEApplication(open('file.xlsx', 'rb').read()) # attachment.add_header('Content-Disposition', 'attachment', filename='file.xlsx') # msg.attach(attachment) #jpg型別附件 # attachment = MIMEApplication(open('file.jpg', 'rb').read()) # attachment.add_header('Content-Disposition', 'attachment', filename='file.jpg') # msg.attach(attachment) #mp4型別附件 # attachment = MIMEApplication(open('file.mp4', 'rb').read()) # attachment.add_header('Content-Disposition', 'attachment', filename='file.mp4') # msg.attach(attachment) #HTML附件 attachment = MIMEApplication(open(self.file, 'rb').read()) attachment.add_header('Content-Disposition','attachment',filename ='自動化測試報告.html') msg.attach(attachment) #登入併發送郵件 try: smtp = smtplib.SMTP_SSL(smtpserver,smtplib.SMTP_SSL_PORT) log().getLogger().info(f"{smtp}連線成功") smtp.login(msg_from, password) log().getLogger().info(f"{smtp}登陸成功") smtp.sendmail(msg_from, msg_to, msg.as_string()) log().getLogger().info(f"{smtp}傳送郵件成功") smtp.quit() except smtplib.SMTPException as e: log().getLogger().error("傳送郵件失敗") if __name__ == '__main__': SendMail().send_mail_html()
效果如下圖:
三十六般武藝,七十二般變化,修練出個人品牌併發出光芒