import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr
from typing import List, Union

from ddans.native.hook import NHook
from ddans.native.log import NLog
from ddans.descriptor.singleton import SingletonMeta


class SEmailer(metaclass=SingletonMeta):

    def __init__(self, smtp_server, smtp_port, from_addr, password):
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.from_addr = from_addr
        self.password = password

    def send(self,
             to_addr: Union[str, List[str]],
             subject,
             body,
             from_addr='yury'):

        if isinstance(to_addr, str):
            to_addr = [to_addr]

        if not NHook.isvalid(to_addr):
            return

        # 创建一个MIMEMultipart对象，用于包含邮件的多个部分
        msg = MIMEMultipart()
        msg['From'] = formataddr((from_addr, self.from_addr), 'utf-8')  # 发送者名称
        msg['To'] = ", ".join(to_addr)
        msg['Subject'] = Header(subject, 'utf-8')  # 邮件主题

        # 邮件正文内容
        msg.attach(MIMEText(body, 'html', 'utf-8'))

        try:
            # 创建SMTP对象，并连接到SMTP服务器
            server = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
            server.login(self.from_addr, self.password)  # 登录SMTP服务器
            server.sendmail(self.from_addr, to_addr, msg.as_string())  # 发送邮件
            server.quit()
            NLog.success("邮件发送成功")
            # NLog.success(f"{msg.as_string()}")
        except smtplib.SMTPException as e:
            NLog.error(f"邮件发送失败: {e}")
