pythonでデータベースの内容を検索してexcelメールを自動的に送信


入社して半年になりブログを書き始め、記念して、ついでに自分の経験を分かち合います.
入社1週目に受け取ったプロジェクトは、データベースから一致するデータを検索し、excelを介してディメンション・グループ・メンバーに送信するためのスクリプトです.
会社のこのプロジェクトはpython 2を使っているからです.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()