定时执行任务,发送带excel附件及excel内容展示邮件

摘要:
具体参看如下代码importrequests,codecsimportpandasaspdimportosimportsmtplib,os,jsonfromemail.mime.multipartimportMIMEMultipartfromemail.mime.textimportMIMETextfromemail.mime.applicationimportMIMEApplicationfro

具体参看如下代码

importrequests,codecs
importpandas as pd
importos

importsmtplib,os,json
from email.mime.multipart importMIMEMultipart
from email.mime.text importMIMEText
from email.mime.application importMIMEApplication

from openpyxl importload_workbook
importreadConfig as Rc



importtime
from apscheduler.schedulers.blocking importBlockingScheduler


importpgSqlQuery as Pq






defmailWrite(filepath,sheet):
    '''写邮件,读取excel文件内容作为邮件正文'''df2 = pd.read_excel(filepath, sheet_name=sheet)
    #设置html存放目录
    htmlfiles = 'pgResultHtml'
    if notos.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)
    #返回文件内容
    returnhtmlContent


defsendEmail(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 inresultFileList:
        #获取结果文件的绝对路径
        resultFilePath =os.path.join(targetPath, resultFileName)

        #---这是文字部分---

        #邮件正文内容

        #打开文件
        #filepath设置详细的文件地址
        filepath =resultFilePath
        #打开结果exel文件
        wb =load_workbook(filepath)
        #获取excel sheet名称
        sheets =wb.sheetnames
        #定义一个存放读取结果的dict
        htmlData ={}

        for sheet insheets:
            #调用excel转化html 函数
            content =mailWrite(filepath,sheet)
            #根据sheet页存储各个sheet的内容
            htmlData[sheet] =content

        contents = ''
        #遍历取出各个sheet的内容
        for ct inhtmlData.keys():
            contents += (ct + ':
' +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

defpgQuery(text):

    
    globali
    #设置文件名
    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))





defpgQueryTask(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()

免责声明:文章转载自《定时执行任务,发送带excel附件及excel内容展示邮件》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇SAP OBYC Account Determination实现checkbox全选、非全选、单选下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

gulp搭建前端自动化开发环境

gulp是基于node编写的一个构建工具,有4个主要的API: gulp.src() - 输出符合条件的文件 gulp.dest() - 能被pipe进来,并写文件 gulp.task() - 定义任务 gulp.watch() - 监听文件   首先,默认node环境已经安装; 全局安装gulp: npm i -g gulp 新建文件夹,npm初始化:n...

express的学习,与使用

最近在学习vue的一个实战项目,碰到一个express,当时很萌,就随便看了看................ expres是基于node 的一个web框架, 首先可以找到它的官网照着学习 这里只讲一些官网上没有的或者很晦涩的东西......... 1)模版引擎的使用 给出package.json的依赖 {  "name": "demo",  "versi...

web页面弹出窗口代码大全

//-----------按钮提示框----------// <input type="button" name="btn2" id="btn2" value="删除" onclick="return confirm('Yes/No');); //-----------按钮提示框----------// <input type="but...

java数据库登陆页面

下面是一些总结但是部分来源于网络。 1.java语言 2. 面向对象分析设计 XML 语言 网页脚本语言 数据库 应用服务器 集成开发环境 .java语言:JSP、Servlet、JDBC、javaBean(Application)从这四部分开始创建web项目。 (一)java Database Connectivity(JBDC)技术 它是一种执行...

巧用javascript ajax,实现跨域请求外带,增大漏洞危害

  今天聊聊javascript ajax发起请求,获取数据:    实在是漏洞挖掘中,经常会用到,学好javascript实在是太有用了    JS原生请求:      XMLHttpRequest(XHR)对象用于与服务器交互。通过 XMLHttpRequest 可以在不刷新页面的情况下请求特定 URL,获取数据。这允许网页在不影响用户操作的情况下,更...

pyquery库的使用

pyquery标签选择 获取了所有的img标签(css选择器,你也可以换成不同的class和id) 1 importrequests 2 importre 3 from pyquery importPyQuery as pq 4 headers={ 5 "Accept": "text/html,application/xhtml+xml,appl...