
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import schedule # type: ignore
import time
from datetime import datetime
import configparser





# 配置信息
SMTP_SERVER = ''  # SMTP服务器地址
SMTP_PORT = ''                   # SMTP端口
SENDER_EMAIL = ''  # 发件邮箱
SENDER_PASSWORD = ''        # 邮箱密码
RECIPIENTS = '' # 收件人列表
FILE_PREFIX = 'tilt_report_'             # 文件前缀
FILE_PREFIX2 = 'vibration_report_'             # 文件前缀
FILE_DIR = './report'                   # 文件目录



def get_today_filename():
    """获取当天日期的文件名"""
    # today = datetime.now().strftime('%Y%m%d')
    today = str(datetime.now().date()).replace("-", "")
    return [f"{FILE_PREFIX}{today}.xlsx",f"{FILE_PREFIX2}{today}.xlsx"]

def send_email(SMTP_SERVER,SMTP_PORT,SENDER_EMAIL,SENDER_PASSWORD,RECIPIENTS):
    """发送邮件函数"""
    filename = get_today_filename()
    filepath = os.path.join(FILE_DIR, filename[0])
    filepath2 = os.path.join(FILE_DIR, filename[1])
    
    
    if not os.path.exists(filepath):
        print(f"文件 {filename[0]} 不存在")
        return
    if not os.path.exists(filepath2):
        print(f"文件 {filename[1]} 不存在")
        return

    msg = MIMEMultipart()
    msg['From'] = SENDER_EMAIL
    msg['To'] = ', '.join(RECIPIENTS)
    msg['Subject'] = f"每日报告 - {datetime.now().strftime('%Y-%m-%d')}"

    # 添加附件
    with open(filepath, 'rb') as f:
        part = MIMEApplication(f.read(), Name=filename[0])
    part['Content-Disposition'] = f'attachment; filename="{filename[0]}"'
    msg.attach(part)
    with open(filepath2, 'rb') as f:
        part = MIMEApplication(f.read(), Name=filename[1])
    part['Content-Disposition'] = f'attachment; filename="{filename[1]}"'
    msg.attach(part)


    try:
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()
        server.login(SENDER_EMAIL, SENDER_PASSWORD)
        server.sendmail(SENDER_EMAIL, RECIPIENTS, msg.as_string())
        server.quit()
        print(f"{datetime.now()}: 邮件发送成功")
    except Exception as e:
        print(f"邮件发送失败: {str(e)}")


def job():
    """定时任务"""
    print(f"{datetime.now()}: 开始执行发送任务")

        # 创建ConfigParser对象并读取INI文件
    config = configparser.ConfigParser()
    config.read('./config.ini')  # 确保路径正确，替换为你的文件名
    SMTP_SERVER = config['EMAIL']['SMTP_SERVER']# SMTP服务器地址
    SMTP_PORT = config.get('EMAIL','SMTP_PORT' )                 # SMTP端口
    SENDER_EMAIL = config['EMAIL']['SENDER_EMAIL']  # 发件邮箱
    SENDER_PASSWORD = config['EMAIL']['SENDER_PASSWORD']        # 邮箱密码
    RECIPIENTS = config.get('EMAIL', 'RECIPIENTS').split(',') # 收件人列表

    send_email(SMTP_SERVER,SMTP_PORT,SENDER_EMAIL,SENDER_PASSWORD,RECIPIENTS)

if __name__ == '__main__':


    # 每天8:30执行
    print("邮件自动发送程序已启动...") 
    # 创建ConfigParser对象并读取INI文件
    config = configparser.ConfigParser()
    config.read('./config.ini')  # 确保路径正确，替换为你的文件名    
    EMAIL_TIME= config['REPORTTIME']['EMAIL_TIME']
    schedule.every().day.at(EMAIL_TIME).do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(60)
