77 lines
2.6 KiB
Python
77 lines
2.6 KiB
Python
"""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:
|
||
line = f"#{c['ticket_number']} {c['ticket_title']}\n {c['label']}: {c.get('old_value') or '–'} -> {c.get('new_value') or '–'}"
|
||
if c.get("detail"):
|
||
line += f"\n {c['detail']}"
|
||
lines.append(line)
|
||
body = (
|
||
f"Es gibt {len(changes)} neue Änderung(en) an euren EPI-Support-Tickets:\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)} Ticket-Ä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)
|