python自动化报表,并以邮件方式发送到指定邮箱

1 篇文章 0 订阅
1 篇文章 0 订阅

实现功能:从数据库中,查询数据,把数据保存为excel文件,并通过邮件发送到指定邮箱。具体细节,如下:

#coding:utf-8
import pandas as pd
import numpy as np
import pymysql
import openpyxl
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import smtplib
import sys
import traceback

def getYesterday(): #返回昨天日期

today = datetime.date.today()

oneday = datetime.timedelta(days=1)

yesterday = today - oneday

yesterdaystr = yesterday.strftime('%Y-%m-%d')

return yesterdaystr

def get_mysql_data(sql_order): #返回数据库查询数据
conn = pymysql.connect(host=“localhost”, port=3306, user="**", password="", db="f", charset=“utf8”)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

try:
    cursor.execute(sql_order)
    data=cursor.fetchall()
     # col_result=cursor.description               #字段描述
    frame=pd.DataFrame(data)

except:
    frame=pd.DataFrame()
return frame

cursor.close()
conn.commit()
conn.close()

input_sql=input(“请输入sql语句:”)
new_DataFrame1=get_mysql_data(input_sql) #cursor,‘select * from ex’

new_DataFrame2=new_DataFrame1.copy()

#print(new_DataFrame1.columns)
columns=[“slotid”,“shows”,“clicks”,“income”,“fillrate”]
new_file=“Data-”+getYesterday()+".xlsx"
file_path=“D:\hello”+"\"+new_file
data_to_excel=new_DataFrame1.to_excel(file_path,columns=columns) #保存到excel文件,单个sheet表
#print(data_to_excel)

def create_email(eamil_from,email_to,email_subject,email_text,annex_path,annex_name): #创建email

message=MIMEMultipart()                                      #生成一个空的带附件的邮件实例

message.attach(MIMEText(email_text,"plain","utf-8"))        #将正文以文本的形式插入到邮件中

message["from"]=Header(eamil_from,"utf-8")                  #生成发件人名称

message["to"]=Header(email_to,"utf-8")                      #生成收件人名称

message["Subject"]=Header(email_subject,"utf-8")            #生成邮件主题

att1=MIMEText(open(annex_path,"rb").read(),"base64","utf-8")    #读取附件内容
att1["Content-Type"]="application/octet-stream"

att1["Content-Disposition"]="attachment;filename="+annex_name       #生成附件的名称

message.attach(att1)                                                     #将附件内容插入到邮件中

return message

def send_email(sender,password,receiver,msg): #发送email
try:
server=smtplib.SMTP_SSL(“smtp.qq.com”,465) #找到发送邮箱的服务器地址
server.ehlo()

    server.login(sender,password)                                         #登录我的邮箱

    server.sendmail(sender,receiver,msg.as_string())                      #发送邮件,发件人和收件人的账号以及邮件内容
    print("发送成功")
    server.quit()                                                         #关闭连接
except Exception:
    print(traceback.print_exc())
    print("发送失败")

def main():
print(datetime.datetime.now()) #打印当前日期

yesterdaystr=getYesterday()                                                 #获取昨天的日期

#my_file_name="double"+".xlsx"                                              #附件的名称

file_path = "D:\hello" + "\\" + new_file                                      #附件所在路径

my_file_from="BI"                                                            #邮件发送方命名

my_file_to="运营部"                                                          #邮件接收方命名

my_email_Subject=yesterdaystr+"--"+"数据报表"                                #邮件主题

my_email_text=r"Dear all:  附件为数据。--from: BI"                         #邮件内容

my_annex_path=file_path                                                       #附件存在的路径

my_annex_name=new_file                                                      #附件的名字

my_msg=create_email(my_file_from,my_file_to,my_email_Subject,my_email_text,my_annex_path,my_annex_name) #传参

my_sender="842*****451@qq.com"
my_password="d*w***dno***s*b**f"
my_receiver=["liu*********.com"]

send_email(my_sender,my_password,my_receiver,my_msg)
print(datetime.datetime.now())

if name==“main”:
main()

以上是完整的项目代码,不足之处,望包涵指正!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值