# Author renyupeng # coding=utf-8 # @Time : 2024/9/26 16:08 # @Site : # @File : CanalEmail.py # @Software: PyCharm # @contact: renyupeng@c-top.com.cn # @Tel 1501435553 import datetime import urllib from urllib import parse import pandas as pd import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from sqlalchemy import create_engine class CanalEmail: def __init__(self): self.OuterStr = "mysql+pymysql://%s:%s@%s:%d/%s" % ( "data", parse.quote_plus("hcst@2021"), "139.186.27.96", 3390, "application") self.OuterConn = create_engine(self.OuterStr, pool_size=10, max_overflow=5, pool_timeout=10, pool_recycle=3600) self.stat_date = (datetime.date.today() + datetime.timedelta(0)).strftime("%Y%m%d") def handler(self, keys, values): sql = """ select t.*, ifnull(tt.promoterCount,'-') as '(总)达人数', ifnull(ttt.sampleCount,'-') as '(总)领样达人数', ifnull(tttt.sendTotalCount,'-') as '发样数', ifnull(tttt.sendPromoterCount,'-') as '发样商品数', ifnull(tttt.sendItemCount,'-') as '发样商品数' from (select t5.reg_name as `团名称`, t1.user_id as 'collectSampleId', t1.user_name as '绑定人名称', ifnull(count(t2.oid),'-') as '订单数', sum(case when order_status != 80 then 1 else 0 end) as '有效出单数', round(sum(case when order_status != 80 then 1 else 0 end) / count(oid) * 100, 2) as '有效率', round(sum(case when order_status != 80 then pay_amount else 0 end) / 100, 2) as 'Gvm', ifnull(round(sum(t2.order_amount) / 100, 2),'-') as '金额', ifnull(round(sum(t2.regimental_promotion_amount) / 100, 2) ,'-') as '预估服务费收入', ifnull( round(sum(t2.total_regimental_settle_amount) / 100, 2) ,'-') as '结算服务费收入' from {database}.promoter_bind_channel_date t1 left join {database}.kuaishou_supply_chain t2 on t1.promoter_id = t2.promoter_id and t1.stat_date = t2.stat_date left join (select id,reg_name from ruixuan.kuaishou_supply_chain_cookie union all select id,reg_name from miaogousi.kuaishou_supply_chain_cookie union all select id,reg_name from yufu.kuaishou_supply_chain_cookie union all select id,reg_name from rocket.kuaishou_supply_chain_cookie union all select id,reg_name from zhishui.kuaishou_supply_chain_cookie union all select id,reg_name from yuxiu.kuaishou_supply_chain_cookie group by id, reg_name)t5 on t2.regimental_id=t5.id where 1 = 1 and t1.media_id = 2 and t1.stat_date >= DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%%Y%%m01') and t1.stat_date <= DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 1 MONTH), '%%Y%%m%%d') group by t2.regimental_id,t1.user_id) t left join (select user_id, count(distinct promoter_id) as 'promoterCount' from {database}.kuaishou_promoter group by user_id) tt on t.collectSampleId = tt.user_id left join (select collect_sample_id as 'user_id', count(distinct promoter_id) as 'sampleCount' from {database}.kuaishou_item_collect_samples where collect_sample_status > 2 group by collect_sample_id) ttt on t.collectSampleId = ttt.user_id left join (select collect_sample_id as 'user_id', count(1) as 'sendTotalCount', count(distinct promoter_id) as 'sendPromoterCount', count(distinct item_id) as 'sendItemCount' from {database}.kuaishou_item_collect_samples where collect_sample_status > 2 and create_time >= DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%%Y-%%m-01') and create_time < date_sub(DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 1 MONTH), '%%Y-%%m-%%d'),interval -1 day) group by collect_sample_id) tttt on t.collectSampleId = tttt.user_id left join (select user_id, promoters_count from {database}.user_promoters_count where media_id = 2) ttttt on t.collectSampleId = ttttt.user_id where t.订单数 > 0 order by t.订单数 desc """.format(database=keys) print(sql) path = """/data/excel/渠道-{database}-{stat_date}.xls""".format(database=values, stat_date=self.stat_date) print(path) pd.read_sql(sql, self.OuterConn).to_excel(path, index=False, engine='openpyxl') my_sender = 'renyupeng@c-top.com.cn' # 发件人邮箱账号 my_pass = 'fcyJKkHUyPo6Zztw' # 发件人邮箱授权码 / 腾讯企业邮箱请使用登陆密码 recipients = ['niuxiaoyu@c-top.com.cn', 'lishiwei@c-top.com.cn'] # 收件人邮箱账号 # content = "Please check the attachment. " msg = MIMEMultipart() # [发件人的邮箱昵称、发件人邮箱账号], 昵称随便 msg['From'] = my_sender # [收件人邮箱昵称、收件人邮箱账号], 昵称随便 msg['To'] = ",".join(recipients) # 邮件的主题,也就是邮件的标题 msg['Subject'] = "渠道-{}".format(values) att1 = MIMEText( open(path, 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' filename = '{key}-{stat_date}.xlsx'.format(key=keys, stat_date=self.stat_date) encoded_filename = urllib.parse.quote(filename) att1["Content-Disposition"] = 'attachment; filename="{encoded_filename}"'.format( encoded_filename=encoded_filename) msg.attach(att1) server = smtplib.SMTP_SSL("smtp.exmail.qq.com", port=465) server.login(my_sender, my_pass) try: server.sendmail(my_sender, recipients, msg.as_string()) print("发送成功") except Exception as e: print("发送失败", e) if __name__ == '__main__': database_mapping = {'yufu': '渔夫', 'miaogousi': '食品', 'ruixuan': '服装', 'rocket': '年轻', 'yuxiu': '玉秀','zhishui':'止水'} for key, value in database_mapping.items(): CanalEmail().handler(key, value)