import smtplib
from email.message import EmailMessage

from config import Config


def build_from_header(from_email: str, from_name: str | None = None) -> str:
    if from_name:
        return f"{from_name} <{from_email}>"
    return from_email



def send_mail(settings: dict, recipient: str, subject: str, text_body: str):
    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = build_from_header(settings["from_email"], settings.get("from_name"))
    msg["To"] = recipient
    msg.set_content(text_body)

    with smtplib.SMTP(settings["host"], settings["port"], timeout=Config.MAIL_TIMEOUT) as smtp:
        smtp.ehlo()
        if settings.get("use_tls", True):
            smtp.starttls()
            smtp.ehlo()
        smtp.login(settings["username"], settings["password"])
        smtp.send_message(msg)
