具體參看如下代碼
import requests,codecs import pandas as pd import os import smtplib,os,json from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication from openpyxl import load_workbook import readConfig as Rc import time from apscheduler.schedulers.blocking import BlockingScheduler import pgSqlQuery as Pq def mailWrite(filepath,sheet): '''寫郵件,讀取excel文件內容作為郵件正文''' df2 = pd.read_excel(filepath, sheet_name=sheet) # 設置html存放目錄 htmlfiles = 'pgResultHtml' if not os.path.exists(htmlfiles): os.mkdir(htmlfiles) htmlName = sheet + '.html' htmlPath = os.path.join(htmlfiles,htmlName) # 生成html結果文件 with codecs.open(htmlPath, 'w', 'utf-8') as html_file: html_file.write(df2.to_html(header=True, index=False)) # 打開並讀取html結果文件內容 with open(html_file.name,'r') as html_f: htmlContent = html_f.read() # print(htmlContent) # 返回文件內容 return htmlContent def sendEmail(fileName): '''發送帶附近及展示附件內容郵件''' rc = Rc.ReadConfig() Smtp_Server = rc.getEmailInfo('Smtp_Server') sender = rc.getEmailInfo('Smtp_Sender') pwd = rc.getEmailInfo('Password') receiver = rc.getEmailInfo('Pre_Receiver') Msg_Title = rc.getEmailInfo('Msg_Title') Text_description = rc.getEmailInfo('Text_description') Receiver = [] for receiver in receiver.split(','): Receiver.append(receiver) _user = sender _pwd = pwd _to = Receiver print(_to) # 如名字所示Multipart就是分多個部分 msg = MIMEMultipart() msg["Subject"] = Msg_Title msg["From"] = _user msg["To"] = ",".join(_to) print(msg['To']) # ---這是附件部分--- currentPath = os.getcwd() sqldataFile = os.path.join(currentPath, 'sqlDataFiles') targetPath = os.path.join(sqldataFile, fileName) # 獲取目標目錄下的郵件附件 resultFileList = os.listdir(targetPath) # 發送多個附件的郵件,這里發送指定目錄下所有類型一致的文件 for resultFileName in resultFileList: # 獲取結果文件的絕對路徑 resultFilePath = os.path.join(targetPath, resultFileName) # ---這是文字部分--- # 郵件正文內容 # 打開文件 # filepath設置詳細的文件地址 filepath = resultFilePath # 打開結果exel文件 wb = load_workbook(filepath) # 獲取excel sheet名稱 sheets = wb.sheetnames # 定義一個存放讀取結果的dict htmlData = {} for sheet in sheets: # 調用excel轉化html 函數 content = mailWrite(filepath,sheet) # 根據sheet頁存儲各個sheet的內容 htmlData[sheet] = content contents = '' # 遍歷取出各個sheet的內容 for ct in htmlData.keys(): contents += (ct + ':\n' + htmlData[ct]) # 設置郵件正文 Text_description = Text_description + contents html = MIMEText(Text_description, 'html', 'utf-8') msg.attach(html) # 設置郵件附件 with open(resultFilePath, 'rb') as f: part = MIMEApplication(f.read()) part.add_header('Content-Disposition', 'attachment', filename=resultFileName) msg.attach(part) s = smtplib.SMTP(Smtp_Server, 25) # 連接smtp郵件服務器,端口默認是25 s.login(_user, _pwd) # 登陸服務器 s.sendmail(_user, _to, msg.as_string()) # 發送郵件 s.close() # 設置初始值 i =46 def pgQuery(text): global i # 設置文件名 weekFileName = 'W' + str(i) # 執行pg 查詢,傳遞文件名,告知執行哪個文件下的sql sqlquery = Pq.PgSqlQuery(weekFileName) sqlquery.readSql() t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 因為每周執行一次,每周執行目錄不同,所以這里累加1,到下一個目錄下 i = i+ 1 # 發送郵件 sendEmail(weekFileName) print('{} --- {}'.format(text, t)) def pgQueryTask(text): ''' 定時任務,保證當前headers 持續有效''' currentPath = os.getcwd() rc = Rc.ReadConfig() payload = rc.getPgSQLInfo('payload') payload = json.loads(payload) url = rc.getPgSQLInfo('url') headers = rc.getPgSQLInfo('headers') headers = json.loads(headers) sqlPath = os.path.join(currentPath,'sql.txt') response = requests.request("POST", url, data=payload, headers=headers) print(response) print(response.json()) t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) print('{} --- {}'.format(text, t)) scheduler = BlockingScheduler() # 設置每周5 上午 10:30執行一次 scheduler.add_job(pgQuery, 'cron', day_of_week=2, hour=16,minute=32, args=['pgQuery']) scheduler.add_job(pgQueryTask, 'interval', hours = 1,minutes = 56, args=['pgQueryTask']) scheduler.start()
