# ============================================================
# ADDITIVE: Per-company SMTP - validation, duplicate rules, config selection, routing, delivery, logging.
# Pure helpers (no HTTP).  Used by mail_backend.py and views_mail.py.
#
# B2B rules enforced here:
#   * a mail is sent with the SMTP account of the RECIPIENT'S company (employee / candidate rows carry the company)
#   * one company can never see, use or edit another company's configuration
#   * duplicates are blocked: same name, same mailbox (host + user) inside a company, a second default for an audience,
#     and (by default) the same mailbox registered by two different companies
# ============================================================
import copy
import ipaddress
import re
import smtplib
import socket
import ssl
import uuid
from collections import OrderedDict
from datetime import datetime, time, timedelta
from email.utils import formataddr

from django.conf import settings
from django.core.mail import EmailMessage
from django.core.mail.backends.smtp import EmailBackend as DjangoSMTPBackend
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import Q
from django.utils import timezone

from Employee.models import EmployeeDT

from . import mail_context, mail_crypto
from .common import employees_qs
from .models import CompanyEmailConfig, CompanyEmailLog

HOST_RE = re.compile(r"^(?=.{1,253}$)[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$")
DEFAULT_PORTS = (25, 465, 587, 2525)
AUDIENCES = [a for a, _ in CompanyEmailConfig.AUDIENCES]
SECURITIES = [s for s, _ in CompanyEmailConfig.SECURITY]
KIND_WORDS = (("interview", "interview"), ("offer", "offer"), ("joining", "joining"), ("application details", "candidate_portal"),
              ("upload your", "candidate_portal"), ("welcome", "welcome"), ("transfer", "transfer"), ("reset", "password"))

PRESETS = [   # starting points shown in the UI (host/port/security can still be edited)
    {"key": "gmail", "label": "Gmail / Google Workspace", "host": "smtp.gmail.com", "port": 587, "security": "STARTTLS",
     "help": "Use an App Password (Google account -> Security -> App passwords). The normal password is rejected."},
    {"key": "office365", "label": "Microsoft 365 / Outlook", "host": "smtp.office365.com", "port": 587, "security": "STARTTLS",
     "help": "SMTP AUTH must be enabled for the mailbox in the Microsoft 365 admin centre."},
    {"key": "titan", "label": "Titan / BigRock", "host": "smtp.titan.email", "port": 465, "security": "SSL",
     "help": "Username is the full mailbox address."},
    {"key": "zoho", "label": "Zoho Mail", "host": "smtp.zoho.in", "port": 465, "security": "SSL",
     "help": "Use smtp.zoho.com for the .com data centre. App-specific password recommended."},
    {"key": "sendgrid", "label": "SendGrid", "host": "smtp.sendgrid.net", "port": 587, "security": "STARTTLS",
     "help": "Username is the word apikey, password is your API key. From address must be a verified sender."},
    {"key": "ses", "label": "Amazon SES", "host": "email-smtp.ap-south-1.amazonaws.com", "port": 587, "security": "STARTTLS",
     "help": "Use the SMTP credentials created in SES (not your IAM password)."},
    {"key": "custom", "label": "Custom SMTP server", "host": "", "port": 587, "security": "STARTTLS", "help": ""},
]


class MailConfigError(Exception):
    pass


class MailLimitError(MailConfigError):
    pass


class FieldError(ValueError):
    def __init__(self, field, message):
        super().__init__(message)
        self.field = field


# ================================================================ validation
def norm_name(v):
    return re.sub(r"\s+", " ", str(v or "").strip())


def check_host(host):
    """Block internal addresses (SSRF): a tenant must not be able to make the server talk to its own network."""
    allow = getattr(settings, "COMPANY_SMTP_ALLOW_PRIVATE_HOSTS", False)
    try:
        ips = [ipaddress.ip_address(host)]
    except ValueError:
        if not allow and (host == "localhost" or host.endswith((".local", ".localhost", ".internal", ".lan"))):
            raise FieldError("host", "This host name points to an internal network and is not allowed.")
        if not getattr(settings, "COMPANY_SMTP_VERIFY_DNS", True):
            return
        try:
            ips = [ipaddress.ip_address(i[4][0]) for i in socket.getaddrinfo(host, None)]
        except (socket.gaierror, ValueError, UnicodeError):
            raise FieldError("host", "This host name could not be resolved. Check the spelling.")
    if not allow:
        for ip in ips:
            if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved or ip.is_unspecified:
                raise FieldError("host", "This host points to a private / internal network address and is not allowed.")


def check_port(port):
    allowed = getattr(settings, "COMPANY_SMTP_ALLOWED_PORTS", DEFAULT_PORTS)
    if allowed is not None and port not in allowed:
        raise FieldError("port", "Port must be one of " + ", ".join(str(p) for p in allowed) + ".")


def _email(v, field, required):
    v = str(v or "").strip()
    if not v:
        if required:
            raise FieldError(field, f"{field} is required.")
        return ""
    try:
        validate_email(v)
    except ValidationError:
        raise FieldError(field, f"{field} is not a valid email address.")
    return v


def _int(v, field, lo, hi):
    try:
        n = int(v)
    except (TypeError, ValueError):
        raise FieldError(field, f"{field} must be a whole number.")
    if n < lo or n > hi:
        raise FieldError(field, f"{field} must be between {lo} and {hi}.")
    return n


def clean_config(d, existing=None):
    """Validate a create / partial-update payload. Returns (fields, new_plain_password_or_None, warnings)."""
    out, warnings, create = {}, [], existing is None
    if create or "name" in d:
        name = norm_name(d.get("name"))
        if len(name) < 2 or len(name) > 80:
            raise FieldError("name", "name is required (2 to 80 characters).")
        out["name"] = name
    if create or "audience" in d:
        aud = str(d.get("audience") or "ALL").strip().upper()
        if aud not in AUDIENCES:
            raise FieldError("audience", "audience must be ALL, EMPLOYEE or CANDIDATE.")
        out["audience"] = aud
    if create or "host" in d:
        host = str(d.get("host") or "").strip().lower()
        if "://" in host or "/" in host or " " in host:
            raise FieldError("host", "host must be a bare server name such as smtp.gmail.com (no http:// or path).")
        try:
            ipaddress.ip_address(host)
        except ValueError:
            if not HOST_RE.match(host):
                raise FieldError("host", "host is not a valid server name.")
        out["host"] = host
    if create or "port" in d:
        out["port"] = _int(d.get("port", 465 if create else None), "port", 1, 65535)
    if create or "security" in d:
        sec = str(d.get("security") or "SSL").strip().upper()
        if sec not in SECURITIES:
            raise FieldError("security", "security must be SSL, STARTTLS or NONE.")
        out["security"] = sec
    if create or "username" in d:
        u = str(d.get("username") or "").strip()
        if len(u) > 254:
            raise FieldError("username", "username is too long (max 254).")
        out["username"] = u
    password = None
    if "password" in d and d["password"] not in (None, ""):
        password = str(d["password"])
        if len(password) > 500:
            raise FieldError("password", "password is too long (max 500).")
    if create or "from_email" in d:
        out["from_email"] = _email(d.get("from_email"), "from_email", True)
    if create or "reply_to" in d:
        out["reply_to"] = _email(d.get("reply_to"), "reply_to", False)
    if create or "from_name" in d:
        fn = str(d.get("from_name") or "").strip()
        if len(fn) > 100 or any(c in fn for c in "\r\n"):
            raise FieldError("from_name", "from_name is too long (max 100) or contains line breaks.")
        out["from_name"] = fn
    if create or "timeout_seconds" in d:
        out["timeout_seconds"] = _int(d.get("timeout_seconds", 20), "timeout_seconds", 5, 60)
    if create or "daily_limit" in d:
        out["daily_limit"] = _int(d.get("daily_limit", 500), "daily_limit", 0, 1000000)
    if create and out.get("username") and not password:
        raise FieldError("password", "password is required when a username is given.")
    host, port = out.get("host", getattr(existing, "host", None)), out.get("port", getattr(existing, "port", None))
    if "host" in out:
        check_host(out["host"])
    if "port" in out:
        check_port(out["port"])
    sec = out.get("security", getattr(existing, "security", "SSL"))
    user = out.get("username", getattr(existing, "username", ""))
    if sec == "NONE" and (user or password):
        warnings.append("Encryption is off: the username and password are sent to the mail server in clear text.")
    if sec == "SSL" and port == 587:
        warnings.append("Port 587 normally uses STARTTLS, not SSL.")
    if sec == "STARTTLS" and port == 465:
        warnings.append("Port 465 normally uses SSL, not STARTTLS.")
    return out, password, warnings


def mailbox_key(host, username, from_email):
    return f"{(host or '').lower()}|{(username or from_email or '').strip().lower()}"


def find_duplicate(company, fields, exclude_pk=None):
    """Return (field, message) when this configuration duplicates an existing one, else None."""
    qs = CompanyEmailConfig.objects.all()
    if exclude_pk:
        qs = qs.exclude(pk=exclude_pk)
    mine = qs.filter(company=company)
    clash = mine.filter(name_key=fields["name_key"]).first()
    if clash:
        return "name", f"A configuration named '{clash.name}' already exists in your company."
    clash = mine.filter(mailbox_key=fields["mailbox_key"]).first()
    if clash:
        return "mailbox", (f"This mailbox is already configured as '{clash.name}'. Edit that configuration, "
                           f"or set its audience to 'Employees & Candidates' to use one mailbox for both.")
    if not getattr(settings, "COMPANY_SMTP_ALLOW_SHARED_MAILBOX", False):
        if qs.filter(mailbox_key=fields["mailbox_key"]).exclude(company=company).exists():
            return "mailbox", "This mailbox is already registered by another company account and cannot be shared."
    return None


def fix_defaults(company):
    """Exactly one default per audience that has enabled configurations."""
    for aud in AUDIENCES:
        rows = list(CompanyEmailConfig.objects.filter(company=company, audience=aud, enabled=True).order_by("id"))
        defaults = [r for r in rows if r.is_default]
        keep = defaults[0] if defaults else (rows[0] if rows else None)
        for r in rows:
            want = r is keep
            if r.is_default != want:
                CompanyEmailConfig.objects.filter(pk=r.pk).update(is_default=want)
        CompanyEmailConfig.objects.filter(company=company, audience=aud, enabled=False, is_default=True).update(is_default=False)


def save_config(company, cfg, fields, password, actor, make_default=False):
    """Create / update inside one transaction; maps unique-constraint races to a duplicate error."""
    for k, v in fields.items():
        setattr(cfg, k, v)
    if password is not None:
        cfg.password_enc = mail_crypto.encrypt(password)
    cfg.name_key = cfg.name.lower()
    cfg.mailbox_key = mailbox_key(cfg.host, cfg.username, cfg.from_email)
    dup = find_duplicate(company, {"name_key": cfg.name_key, "mailbox_key": cfg.mailbox_key}, cfg.pk)
    if dup:
        raise FieldError(*dup)
    if cfg.pk is None:
        cfg.company, cfg.created_by = company, actor
    cfg.updated_by = actor
    if {"host", "port", "security", "username"} & set(fields) or password is not None:
        cfg.last_test_at = cfg.last_test_ok = None
        cfg.last_test_message = ""
    try:
        with transaction.atomic():
            if make_default and cfg.enabled:
                CompanyEmailConfig.objects.filter(company=company, audience=cfg.audience, is_default=True) \
                    .exclude(pk=cfg.pk).update(is_default=False)
                cfg.is_default = True
            cfg.save()
            fix_defaults(company)
    except IntegrityError:
        raise FieldError("mailbox", "A configuration with the same name or mailbox already exists.")
    cfg.refresh_from_db()
    return cfg


# ================================================================ selection / connection
def choose_config(company, audience):
    rows = list(CompanyEmailConfig.objects.filter(company=company, enabled=True).order_by("-is_default", "id"))
    for aud in (audience, "ALL"):
        for r in rows:
            if r.audience == aud:
                return r
    return None


def format_from(cfg):
    return formataddr((cfg.from_name, cfg.from_email)) if cfg.from_name else cfg.from_email


def smtp_backend(cfg, fail_silently=False):
    pw = mail_crypto.decrypt(cfg.password_enc)
    if pw is None:
        raise MailConfigError("The saved SMTP password cannot be decrypted (the encryption key changed). Re-enter the password.")
    return DjangoSMTPBackend(host=cfg.host, port=cfg.port, username=cfg.username or None, password=pw or None,
                             use_tls=cfg.security == "STARTTLS", use_ssl=cfg.security == "SSL",
                             timeout=cfg.timeout_seconds, fail_silently=fail_silently)


def friendly_error(exc, cfg=None):
    pw = mail_crypto.decrypt(cfg.password_enc) if cfg is not None else None
    if isinstance(exc, MailConfigError):
        msg = str(exc)
    elif isinstance(exc, smtplib.SMTPAuthenticationError):
        msg = f"The mail server rejected the login ({exc.smtp_code}). Check the username and password (Gmail / Outlook need an app password)."
    elif isinstance(exc, ssl.SSLError):
        msg = "TLS/SSL handshake failed. Use SSL for port 465 or STARTTLS for port 587."
    elif isinstance(exc, (smtplib.SMTPSenderRefused,)):
        msg = f"The server refused the sender address ({exc.smtp_code}). The From address must belong to this mailbox."
    elif isinstance(exc, smtplib.SMTPRecipientsRefused):
        msg = "The server refused the recipient address."
    elif isinstance(exc, (socket.timeout, TimeoutError)):
        msg = f"Connection timed out after {getattr(cfg, 'timeout_seconds', '')} seconds."
    elif isinstance(exc, (ConnectionError, socket.gaierror, OSError, smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected)):
        msg = f"Could not connect to {getattr(cfg, 'host', 'the server')}:{getattr(cfg, 'port', '')} ({type(exc).__name__})."
    else:
        msg = f"{type(exc).__name__}: {exc}"
    if pw:
        msg = msg.replace(pw, "***")
    return msg[:300]


def test_connection(cfg, send_to=None, actor=""):
    """Open + log in (and optionally send a short test mail). Stores the result on the configuration."""
    res = {"connected": False, "sent": False, "message": ""}
    conn = None
    try:
        conn = smtp_backend(cfg)
        conn.open()
        res["connected"] = True
        res["message"] = f"Connected to {cfg.host}:{cfg.port}" + (" and logged in." if cfg.username else ".")
        if send_to:
            _email(send_to, "send_to", True)
            if _recent_tests(cfg) >= 5:
                raise MailConfigError("Test mail limit reached (5 per hour for each configuration).")
            body = (f"This is a test message from {getattr(cfg.company, 'Registered_Company_Name', 'your company')} "
                    f"confirming that the SMTP configuration '{cfg.name}' works.")
            EmailMessage("SMTP test message", body, format_from(cfg), [send_to], connection=conn,
                         reply_to=[cfg.reply_to] if cfg.reply_to else None).send()
            res["sent"] = True
            res["message"] += f" Test mail sent to {send_to}."
            CompanyEmailLog.objects.create(company=cfg.company, config=cfg, config_name=cfg.name, from_email=cfg.from_email,
                                           recipient_type="OTHER", to_email=send_to, subject="SMTP test message",
                                           kind="smtp_test", status="SENT", via="COMPANY_SMTP", sent_by=actor)
    except FieldError:
        raise
    except Exception as exc:                                  # noqa: BLE001 - every failure becomes a friendly message
        res["message"] = friendly_error(exc, cfg)
        res["connected"] = res["connected"] and not isinstance(exc, MailConfigError)
    finally:
        if conn is not None:
            try:
                conn.close()
            except Exception:                                  # noqa: BLE001
                pass
    ok = res["connected"] and (res["sent"] or not send_to)
    cfg.last_test_at, cfg.last_test_ok, cfg.last_test_message = timezone.now(), ok, res["message"][:300]
    cfg.save(update_fields=["last_test_at", "last_test_ok", "last_test_message"])
    res["ok"] = ok
    return res


def _recent_tests(cfg):
    return CompanyEmailLog.objects.filter(config=cfg, kind="smtp_test",
                                          created_at__gte=timezone.now() - timedelta(hours=1)).count()


def sent_today(cfg):
    start = timezone.make_aware(datetime.combine(timezone.localdate(), time.min))
    return CompanyEmailLog.objects.filter(config=cfg, status="SENT", created_at__gte=start).exclude(kind="smtp_test").count()


# ================================================================ routing
class Route:
    def __init__(self, company, cfg, recipients, matches, blocked=False, reason=""):
        self.company, self.cfg, self.recipients, self.matches = company, cfg, recipients, matches
        self.blocked, self.reason = blocked, reason


def platform_fallback_allowed():
    """Company people normally NEVER receive mail through the platform (SuperAdmin) mailbox."""
    return bool(getattr(settings, "COMPANY_MAIL_ALLOW_PLATFORM_FALLBACK", False))


def classify(emails):
    """email(lower) -> {'emp', 'company', 'candidate'} for every recipient that is an employee / candidate row."""
    if not emails:
        return {}
    q = Q()
    for e in emails:
        q |= Q(email__iexact=e)
    rows = list(EmployeeDT.objects.filter(q).select_related("company"))
    out, by_company = {}, {}
    for r in rows:
        by_company.setdefault(r.company_id, []).append(r)
    for cid, emps in by_company.items():
        real = set(employees_qs(emps[0].company).filter(id__in=[e.id for e in emps]).values_list("id", flat=True))
        for e in emps:
            out[(e.email or "").strip().lower()] = {"emp": e, "company": e.company, "candidate": e.id not in real}
    return out


def route_message(msg):
    """Split one message into routes: each route = one SMTP account (or the global fallback) + its recipients."""
    emails = list(OrderedDict.fromkeys(a.strip().lower() for a in msg.recipients() if a and a.strip()))
    if not emails:
        return []
    headers = getattr(msg, "extra_headers", None) or {}
    forced = headers.get("X-HRN-Config")
    info = classify(emails)
    if forced and str(forced).isdigit():
        cfg = CompanyEmailConfig.objects.filter(pk=int(forced), enabled=True).select_related("company").first()
        # a forced configuration is only honoured when no recipient belongs to ANOTHER company (B2B guard)
        if cfg is not None and all(i["company"].id == cfg.company_id for i in info.values()):
            return [Route(cfg.company, cfg, emails, info)]
    ctx = mail_context.current_company()
    routes = OrderedDict()
    for e in emails:
        i = info.get(e)
        company = i["company"] if i else ctx            # an outsider's address, mailed by a company user, is still that company's mail
        audience = ("CANDIDATE" if i["candidate"] else "EMPLOYEE") if i else "EMPLOYEE"
        if company is None:                             # SuperAdmin / public / background mail -> platform SMTP (settings.py)
            key, cfg, blocked = ("platform",), None, False
        else:
            cfg = choose_config(company, audience)
            if cfg:
                key, blocked = ("cfg", cfg.id), False
            elif platform_fallback_allowed():
                key, blocked = ("platform",), False
            else:
                key, blocked = ("blocked", company.id, audience), True
        r = routes.get(key)
        if r is None:
            reason = ""
            if blocked:
                reason = (f"{getattr(company, 'Registered_Company_Name', 'This company')} has no enabled SMTP configuration for "
                          f"{audience.lower()}s. Add one under Email settings - the platform mailbox is never used for company mail.")
            r = routes[key] = Route(company if (cfg or blocked) else None, cfg, [], info, blocked, reason)
        r.recipients.append(e)
    return list(routes.values())


def part_for(msg, route, whole):
    """The message to really send for one route: ALWAYS a copy (the original keeps its X-HRN headers for logging),
    limited to that route's recipients, with internal headers removed and From / Reply-To set to the company mailbox."""
    m = copy.copy(msg)
    if not whole:
        keep = set(route.recipients)
        m.to = [a for a in msg.to if a.strip().lower() in keep]
        m.cc = [a for a in msg.cc if a.strip().lower() in keep]
        m.bcc = [a for a in msg.bcc if a.strip().lower() in keep]
    m.extra_headers = {k: v for k, v in (getattr(msg, "extra_headers", None) or {}).items() if not k.startswith("X-HRN-")}
    if route.cfg is not None:
        m.from_email = format_from(route.cfg)
        if not m.reply_to and route.cfg.reply_to:
            m.reply_to = [route.cfg.reply_to]
    return m


def guess_kind(msg):
    h = getattr(msg, "extra_headers", None) or {}
    if h.get("X-HRN-Kind"):
        return str(h["X-HRN-Kind"])[:40]
    s = (msg.subject or "").lower()
    for word, kind in KIND_WORDS:
        if word in s:
            return kind
    return "general"


def write_logs(route, msg, status, via, error="", batch=""):
    h = getattr(msg, "extra_headers", None) or {}
    rows = []
    for e in route.recipients:
        i = route.matches.get(e)
        if i is None and route.company is None:
            continue                                              # external address with no company: nothing to attach it to
        company = i["company"] if i else route.company
        rows.append(CompanyEmailLog(
            company=company, config=route.cfg, config_name=route.cfg.name if route.cfg else "",
            from_email=route.cfg.from_email if route.cfg else (msg.from_email or ""),
            recipient_type=("CANDIDATE" if i and i["candidate"] else "EMPLOYEE" if i else "OTHER"),
            employee=i["emp"] if i else None, to_email=e, subject=(msg.subject or "")[:250], kind=guess_kind(msg),
            status=status, via=via, error=(error or "")[:500], sent_by=str(h.get("X-HRN-By", ""))[:150], batch_id=batch))
    if rows:
        CompanyEmailLog.objects.bulk_create(rows)


def deliver_via_company(route, msg, whole, conns, batch, fail_silently):
    cfg = route.cfg
    limit = cfg.daily_limit
    if limit and sent_today(cfg) + len(route.recipients) > limit:
        err = f"Daily limit of {limit} emails reached for '{cfg.name}'."
        write_logs(route, msg, "FAILED", "COMPANY_SMTP", err, batch)
        if fail_silently:
            return False
        raise MailLimitError(err)
    part = part_for(msg, route, whole)
    try:
        conn = conns.get(cfg.id)
        if conn is None:
            conn = conns[cfg.id] = smtp_backend(cfg, fail_silently=False)
        n = conn.send_messages([part])
    except Exception as exc:                                      # noqa: BLE001
        write_logs(route, msg, "FAILED", "COMPANY_SMTP", friendly_error(exc, cfg), batch)
        conns.pop(cfg.id, None)
        if fail_silently:
            return False
        raise
    ok = bool(n)
    write_logs(route, msg, "SENT" if ok else "FAILED", "COMPANY_SMTP", "" if ok else "The server accepted no recipients.", batch)
    return ok


def new_batch():
    return str(uuid.uuid4())


def send_to_person(company, emp, subject, text, html=None, kind="general", actor="", audience=None):
    """Send ONE mail to ONE employee / candidate of `company` through that company's own SMTP.
    Never raises: returns {sent, status, message, to, via, from}.  status = SENT | FAILED | NO_SMTP_CONFIG | NO_EMAIL"""
    to = (getattr(emp, "email", "") or "").strip()
    if not to:
        return {"sent": False, "status": "NO_EMAIL", "message": "The person has no email address on file.", "to": None}
    if audience is None:
        audience = "EMPLOYEE" if employees_qs(company).filter(pk=emp.pk).exists() else "CANDIDATE"
    cfg = choose_config(company, audience)
    from django.core.mail import EmailMultiAlternatives
    msg = EmailMultiAlternatives(subject, text, cfg.from_email if cfg else "", [to], headers={"X-HRN-Kind": kind, "X-HRN-By": actor})
    if html:
        msg.attach_alternative(html, "text/html")
    batch = new_batch()
    info = classify([to.lower()])
    if cfg is None:
        reason = (f"No enabled SMTP configuration for {audience.lower()}s. Add one under Email settings; "
                  "the platform mailbox is never used for company mail.")
        write_logs(Route(company, None, [to.lower()], info), msg, "FAILED", "NONE", reason, batch)
        return {"sent": False, "status": "NO_SMTP_CONFIG", "message": reason, "to": to}
    conns = {}
    try:
        good = deliver_via_company(Route(company, cfg, [to.lower()], info), msg, True, conns, batch, False)
        res = {"sent": bool(good), "status": "SENT" if good else "FAILED", "message": "" if good else "The server accepted no recipients."}
    except MailLimitError as ex:
        res = {"sent": False, "status": "FAILED", "message": str(ex)}
    except Exception as ex:                                      # noqa: BLE001
        res = {"sent": False, "status": "FAILED", "message": friendly_error(ex, cfg)}
    finally:
        for c in conns.values():
            try:
                c.close()
            except Exception:                                    # noqa: BLE001
                pass
    res.update({"to": to, "via": cfg.name, "from": cfg.from_email})
    return res
