python查數據庫發郵件

有時候需要將數據庫中的統計信息統計好之後,直接每天定時發郵件。

可用python腳本寫好邏輯後,使用crontab每天定時執行

 

# -*- coding: UTF-8 -*-
import MySQLdb
import smtplib 
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def queryDBdata():    
    #連數據庫
    conn = MySQLdb.connect(host='****', user='***', passwd='****', db='***', port=3307, charset='utf8')
    querySQL="select sum(num),date from (SELECT count(e.order_num) num, date_format(r.order_date,'%Y-%m-%d') date from orders_extension e INNER JOIN commission_order r ON e.order_num=r.order_no where e.ex_cookie like '%bd%' and e.biz_type='COMMISSION' and date_format(r.order_date,'%Y-%m')=date_format(NOW(),'%Y-%m') group by date_format(r.order_date,'%Y-%m-%d')  union ALL  SELECT count(e.order_num) num, date_format(r.order_date,'%Y-%m-%d') date from orders_extension e INNER JOIN order_info  r ON e.order_num=r.order_num where e.ex_cookie like '%bd%' and e.biz_type='PPB' and date_format(r.order_date,'%Y-%m')=date_format(NOW(),'%Y-%m')  group by date_format(r.order_date,'%Y-%m-%d') ) a group by date"
    cur = conn.cursor()
    cur.execute("set names 'utf8'")
    cur.execute(querySQL)
 
    #獲取數據
    data="每天晚上九點自動發統計郵件\n\n"+"|    總訂單數        |        日期                 |"+"\n"
    results = cur.fetchall()
    for r in results:
        data=data+"|    "+str(r[0])+"    "+"|    "+str(r[1])+"    |\n"
      
    return data



def send_mail(content):
    try:
        mailToList=['[email protected]',"[email protected]"]
        sender='[email protected]'
        mailto=",".join(mailToList)
        msg = MIMEMultipart()
        msg['Subject'] = "本月****來源的訂單"
        msg['to'] = mailto
        msg['From'] = sender
        body = MIMEText(content)
        msg.attach(body)
        smtp = smtplib.SMTP('mail.163.com')
        smtp.sendmail(sender,mailToList,msg.as_string())

        smtp.quit()
    except smtplib.SMTPException, e:
        print "error...%d: %s" % (e.args[0], e.args[1])
        
        
        
if __name__=="__main__":
    content=queryDBdata()
    send_mail(content)

 

 

 其中crontab  -e 編輯表達式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章