import smtplib
import logging
import sys
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr

# 添加项目根目录到sys.path
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
if parent_dir not in sys.path:
    sys.path.insert(0, parent_dir)

from config import Config
from logger_config import get_logger

# 获取正确配置的日志记录器
logger = get_logger('mail_util')

class MailUtil:
    @staticmethod
    def send_mail(subject, body, recipients=None):
        """发送邮件

        Args:
            subject: 邮件主题
            body: 邮件内容
            recipients: 收件人列表，如果为None则使用配置中的默认收件人

        Returns:
            bool: 发送是否成功
        """
        if not Config.MAIL_ENABLED:
            logger.info("邮件通知未启用")
            return False

        recipients = recipients or Config.MAIL_TO
        if not recipients:
            logger.warning("未配置收件人")
            return False

        try:
            msg = MIMEMultipart()
            msg['From'] = formataddr((Config.MAIL_FROM, Config.MAIL_USERNAME))
            msg['To'] = ', '.join(recipients)
            msg['Subject'] = subject

            msg.attach(MIMEText(body, 'plain'))

            server = smtplib.SMTP_SSL(Config.MAIL_SERVER, Config.MAIL_PORT)
            
            if Config.MAIL_USERNAME and Config.MAIL_PASSWORD:
                server.login(Config.MAIL_USERNAME, Config.MAIL_PASSWORD)
            
            server.send_message(msg)
            server.quit()
            
            logger.info(f"邮件发送成功: {subject}")
            return True
        except Exception as e:
            logger.error(f"邮件发送失败: {str(e)}")
            return False 
        
if __name__ == "__main__":
    # 测试邮件发送
    result = MailUtil.send_mail("测试邮件", "这是一封测试邮件")
