"""E-Mail-Benachrichtigung über erkannte Änderungen (optional).""" import logging import smtplib from email.message import EmailMessage from . import config log = logging.getLogger("episupport.notify") def send_change_mail(changes: list[dict]) -> None: """Verschickt eine Sammelmail über neue Änderungen. `changes` sind dicts mit ticket_number, ticket_title, label, old_value, new_value, detail. """ if not config.NOTIFY_ENABLED or not changes: return if not (config.SMTP_HOST and config.NOTIFY_TO and config.SMTP_FROM): log.warning("E-Mail aktiviert, aber SMTP/Empfänger unvollständig konfiguriert.") return lines = [] for c in changes: # Einträge ohne Ticketbezug (z. B. EPIRent-Version) ohne "#" ausgeben head = f"#{c['ticket_number']} " if c.get("ticket_number") else "" new = c.get("new_value") or "–" # ohne Vorwert (z. B. neues Ticket, Download-Archiv) keinen Pfeil setzen value = f"{c['old_value']} -> {new}" if c.get("old_value") else new line = f"{head}{c['ticket_title']}\n {c['label']}: {value}" if c.get("detail"): line += f"\n {c['detail']}" lines.append(line) body = ( f"Es gibt {len(changes)} neue Änderung(en):\n\n" + "\n\n".join(lines) + f"\n\nDashboard: {config.ZAMMAD_URL}\n(Quelle: EPI-Support-Monitor)" ) msg = EmailMessage() msg["Subject"] = f"[EPI-Support] {len(changes)} Änderung(en)" msg["From"] = config.SMTP_FROM msg["To"] = ", ".join(config.NOTIFY_TO) msg.set_content(body) try: _send(msg) log.info("Benachrichtigungsmail an %s versendet.", config.NOTIFY_TO) except Exception as e: # noqa: BLE001 log.error("E-Mail-Versand fehlgeschlagen: %s", e) def _send(msg) -> None: """Versand über SMTPS (465) oder SMTP+STARTTLS (587/25).""" if config.SMTP_SSL: with smtplib.SMTP_SSL(config.SMTP_HOST, config.SMTP_PORT, timeout=30) as s: if config.SMTP_USER: s.login(config.SMTP_USER, config.SMTP_PASSWORD) s.send_message(msg) else: with smtplib.SMTP(config.SMTP_HOST, config.SMTP_PORT, timeout=30) as s: s.ehlo() if config.SMTP_STARTTLS: s.starttls() s.ehlo() if config.SMTP_USER: s.login(config.SMTP_USER, config.SMTP_PASSWORD) s.send_message(msg) def send_test_mail() -> None: """Einmalige Testmail (zum Prüfen der SMTP-Einstellungen).""" msg = EmailMessage() msg["Subject"] = "[EPI-Support] Testmail – SMTP funktioniert" msg["From"] = config.SMTP_FROM msg["To"] = ", ".join(config.NOTIFY_TO) msg.set_content( "Dies ist eine Testnachricht des EPI-Support-Monitors.\n" "Wenn du diese Mail erhältst, ist der E-Mail-Versand korrekt eingerichtet." ) _send(msg)