#!/usr/bin/env python # coding: utf-8 import os import time import datetime import requests import pandas as pd from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication import smtplib import subprocess import json # 从环境变量中获取相关信息 mail_host = os.getenv('MAIL_HOST', 'smtp.exmail.qq.com') mail_user = os.getenv('MAIL_USER', 'dba2@uenpay.com') mail_pass = os.getenv('MAIL_PASS', 'Payns123') sender = os.getenv('MAIL_SENDER', 'dba2@uenpay.com') default_to_reciver = 'zhengyu@uenpay.com' default_cc_reciver = 'wangjiesheng@uenpay.com' to_reciver = os.getenv('MAIL_TO_RECEIVER', default_to_reciver).split(',') cc_reciver = os.getenv('MAIL_CC_RECEIVER', default_cc_reciver).split(',') receivers = to_reciver + cc_reciver magic_api_url = os.getenv('MAGIC_API_URL', 'https://magic-api.uenpay.com/ams/report/dayOdNameTradeCollectByChannel') def fetch_data(): try: yesterday = datetime.date.today() - datetime.timedelta(days=1) start_date = yesterday.strftime('%Y-%m-%d') end_date = datetime.date.today().strftime('%Y-%m-%d') # 定义要传递的表单数据 form_data = { 'startDate': start_date, # 开始日期 'endDate': end_date # 结束日期 } # 发送POST请求并传递表单数据 response = requests.post(magic_api_url, data=form_data) print(response) data = response.json()['data'][0] df = pd.DataFrame.from_dict(data, orient='index').reset_index() df.columns = ['通道/O单', '交易金额'] return df except Exception as e: print(f"数据读取失败: {e}") raise def send_email(subject, body, attachment): message = MIMEMultipart() message['From'] = sender message['To'] = ';'.join(to_reciver) message['Cc'] = ';'.join(cc_reciver) message['Subject'] = subject message_txt = MIMEText(body, 'plain', 'utf-8') message.attach(message_txt) with open(attachment, 'rb') as file: message_xlsx = MIMEApplication(file.read(), _subtype='vnd.openxmlformats-officedocument.spreadsheetml.sheet') message_xlsx.add_header('Content-Disposition', 'attachment', filename=attachment) message.attach(message_xlsx) try: with smtplib.SMTP(mail_host, 25) as smtpObj: smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print('邮件发送成功') return True except smtplib.SMTPException as e: print(f'邮件发送失败: {e}') return False def main(): start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print('开始执行:', start_time) df = fetch_data() today = datetime.date.today().strftime('%Y%m%d') filename = f"每日交易量统计-{today}.xlsx" df.to_excel(filename, index=False) email_success = send_email( '每日交易量统计', '你好,\n附件是每日交易量数据统计报表,请查收。\n邮件来源: Kubernetes CronJob(tools/magic-api-sendmail)', filename ) end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print('结束执行:', end_time) # 输出 Prometheus 格式的结果 status = 1 if email_success else 0 print(f'uenpay_senmail_status{{start_time="{start_time}", end_time="{end_time}"}} {status}') if __name__ == "__main__": main()