python 傳送帶有附件的郵件
阿新 • • 發佈:2018-12-13
在selenium執行完成,想要把測試報告和截圖傳送指定的郵箱,需要先把測試報告和截圖資料夾打包成壓縮檔案然後一起傳送,下面就是程式碼:
1.壓縮檔案
import os,zipfile #壓縮檔案 def compression(): try: fantasy_zip = zipfile.ZipFile(壓縮檔案存放路徑,'w') for folder,subfolders,files in os.walk(測試報告資料夾路徑): for file in files: fantasy_zip.wirte(os.path.join(folder,file), os.path.relpath(os.path.join(folder,file),測試報告資料夾路徑), compress_type=zipfile.ZIP_DEFLATED) except: logger.warning('壓縮檔案失敗') raise
2.新增到郵件附件
import mimetype,os from email.mime.base import MIMEBase from email import encoders def annex(): try: data = open(壓縮檔名,'rb') ctype,encoding = mimetype.guess_type(壓縮檔名) if ctype isNone or encoding is not None: ctype = 'application/x-zip-compressed' maintype,subtype = ctype.split('/',1) file_msg = MIMEBase(maintype,subtype) file_msg.set_payload(data.read()) data.close() encoders.encode_base64(file_msg) basename = os.path.basename(壓縮檔名) file_msg.add_header('Content-Disposition', 'attachment', filename=basename) return file_mag except: logger.warning('新增檔案失敗!') raise
3.構造郵件模板
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def data(): """郵件內容""" # 報告位置進行按時間排序,返回一個最新的測試報告檔案,目錄格式和儲存測試報告的一致 report_lists = os.listdir(report['report_file_dir']) report_lists.sort(key=lambda fn: os.path.getmtime(report['report_file_dir'] + '\\' + fn)) report_new_file = os.path.join(report['report_file_dir'], report_lists[-1]) # 讀取最新報告的內容 f = open(report_new_file, 'rb') main_body = f.read() f.close() try: self.compression() message_annex = MIMEMultipart() annex = self.annex() # """構建根容器""" test = MIMEText(main_body,'html','utf-8') message_annex['From'] = "{}".format(email['username']) message_annex['To']=",".join(email['receivers']) message_annex['Subject']="OMS 自動化用例測試報告" # """將文字和附件內容新增到郵件""" message_annex.attach(annex) message_annex.attach(test) fullTest = message_annex.as_string() return fullTest except: logger.error('郵件內容錯誤!!!') raise
4.傳送郵件
import os,time,smtplib
def send_eamil(): try: message = self.data() smtpObj=smtplib.SMTP_SSL(email['host'],465) smtpObj.login(email['username'],email['password']) flag = True while flag: try: smtpObj.sendmail(email['username'],email['receivers'],message) smtpObj.quit() flag = False except: logger.info('傳送失敗!!!正在重新發送...') time.sleep(2) continue logger.info('郵件傳送成功') except: logger.warning('配置有誤!!!') raise
整合起來程式碼如下
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import smtplib,time,os,zipfile,mimetypes class SendEmail(): """傳送郵件""" def send_eamil(self): try: message = self.data() smtpObj=smtplib.SMTP_SSL(email['host'],465) smtpObj.login(email['username'],email['password']) flag = True while flag: try: smtpObj.sendmail(email['username'],email['receivers'],message) smtpObj.quit() flag = False except: logger.info('傳送失敗!!!正在重新發送...') time.sleep(2) continue logger.info('郵件傳送成功') except: logger.warning('配置有誤!!!') raise def data(self): """郵件內容""" # 報告位置進行按時間排序,返回一個最新的測試報告檔案,目錄格式和儲存測試報告的一致 report_lists = os.listdir(report['report_file_dir']) report_lists.sort(key=lambda fn: os.path.getmtime(report['report_file_dir'] + '\\' + fn)) report_new_file = os.path.join(report['report_file_dir'], report_lists[-1]) # 讀取最新報告的內容 f = open(report_new_file, 'rb') main_body = f.read() f.close() try: self.compression() message_annex = MIMEMultipart() annex = self.annex() # """構建根容器""" test = MIMEText(main_body,'html','utf-8') message_annex['From'] = "{}".format(email['username']) message_annex['To']=",".join(email['receivers']) message_annex['Subject']="OMS 自動化用例測試報告" # """將文字和附件內容新增到郵件""" message_annex.attach(annex) message_annex.attach(test) fullTest = message_annex.as_string() return fullTest except: logger.error('郵件內容錯誤!!!') raise def compression(self): """將資料夾壓縮為zip""" try: fantasy_zip = zipfile.ZipFile(report['zip_name'], 'w') for folder,subfolders,files in os.walk(report['report_file_dir']): for file in files: fantasy_zip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder, file), report['report_file_dir']), compress_type=zipfile.ZIP_DEFLATED) fantasy_zip.close() except: logger.warning('資料夾壓縮失敗') raise def annex(self): """將zip新增附件""" try: data = open(report['zip_name'], 'rb') ctype, encoding = mimetypes.guess_type(report['zip_name']) if ctype is None or encoding is not None: ctype = 'application/x-zip-compressed' maintype, subtype = ctype.split('/', 1) file_msg = MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) data.close() encoders.encode_base64(file_msg) basename = os.path.basename(report['zip_name']) file_msg.add_header('Content-Disposition', 'attachment', filename=basename) return file_msg except: logger.warning('檔案新增失敗') raise