通过python查找数据库内容自动发送excel邮件

入职半年了开始写博客,纪念一下,顺便分享自己的经验

入职第一周接到的项目是帮助运维组实现从数据库查找符合匹配的数据,并通过excel发送给运维组人员这样的一个脚本

因为公司这个项目是用python2.7,所以需要修改的地方自己处理一下,基本上复制粘贴就可以使用了

# -*- coding: utf-8 -*
# @File    : sendmail.py
import json
import pymysql
import smtplib
import datetime
import pandas as pd
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

# 查询数据
def query(sql):
    # 初始化mysql连接,不同的数据库替换参数
    db= pymysql.connect(host="localhost",user="root",password="123456",db="python_do",port=3306,autocommit=True)
    cursor = db.cursor()
    sql = sql
    try:
        cursor.execute(sql)
        return cursor.fetchall()
    except:
        print("Error: unable to fetch data")

    db.close()

# 导出到excel
def Export():
#这一段是处理国区时间+8,可以自己在sql里面进行处理(不会的自己找sql大神),也可以直接复制粘贴
    #now = datetime.datetime.now() - datetime.timedelta(hours=8)
    #yestoday = now - datetime.timedelta(days=1)
    #now_string = now.strftime('%Y-%m-%d %H:%M:%S')
    #yestoday_string = yestoday.strftime('%Y-%m-%d %H:%M:%S')
#自己修改excel里面需要的标题
    headers = [u'序号',u'标题']
    #for i in data or []:
    data = query(‘你自己的sql语句’)
    #datalist = []
        #tmp = list(i)
        #tmp[3] += datetime.timedelta(hours=8)
        #tmp[4] += datetime.timedelta(hours=8)
        #datalist.append(tmp)
    genexcel = tablib.Dataset(*data, headers=headers)
    datajson =  json.loads(genexcel.json)
    xlsx = xlwt.Workbook(encoding='utf-8')
    sheet = xlsx.add_sheet('sheet1', True)
    for count, i in enumerate(headers):
        sheet.write(0, count, i)
    
    for count, i in enumerate(datajson):
        for c, j in enumerate(headers):
            sheet.write(count + 1, c, i[j])
    xlsx.save(‘excle.xls')    

# 发送邮件
def SendMail():

    _user = '[email protected]'
    _pwd = "123456"
    _to = ["[email protected]","[email protected]""]
    msg = MIMEMultipart()
    body = MIMEText("每日报障", 'HTML', 'utf-8')
    msg['Subject'] = Header("每日报障", 'utf-8')
    msg['From'] = _user
    msg['To'] =','.join(_to)

    msg.attach(body)

    # 添加附件
    att = MIMEText(open("/home/day/excel.xls", "rb").read(),"base64", "utf-8")  # 打开附件地址

    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename="day.xls"'
    msg.attach(att)

    # 发送邮件
    s = smtplib.SMTP_SSL("smtp.163.com")
    s.login(_user, _pwd)
    s.sendmail(_user, msg['to'].split(','), msg.as_string())

    s.quit()
    print("邮件发送成功")


if __name__ == '__main__':
    Export()
    SendMail()

你可能感兴趣的:(python脚本)