147 lines
4.9 KiB
Python
147 lines
4.9 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
"""Mails bauen und über das SMTP-Relay senden.
|
|
|
|
Verschlüsselung ist Pflicht (STARTTLS oder TLS), das Zertifikat wird immer
|
|
geprüft. Absender ist immer die Adresse des Relays, damit SPF, DKIM und DMARC
|
|
passen; Antworten lenkt die Kopfzeile Reply-To um.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import smtplib
|
|
import ssl
|
|
from collections.abc import Mapping
|
|
from dataclasses import dataclass, field
|
|
from datetime import UTC, datetime
|
|
from email.message import EmailMessage
|
|
from email.utils import format_datetime, formataddr, make_msgid
|
|
from types import TracebackType
|
|
|
|
from surveybox.mail.config import MailConfig
|
|
|
|
TIMEOUT_SECONDS = 30
|
|
|
|
|
|
class PermanentError(Exception):
|
|
"""Der Server lehnt die Mail endgültig ab (5xx); ein neuer Versuch hilft nicht."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Outgoing:
|
|
recipient: str
|
|
subject: str
|
|
text: str
|
|
html: str | None = None
|
|
reply_to: str | None = None
|
|
headers: Mapping[str, str] = field(default_factory=dict)
|
|
|
|
|
|
def _one_line(value: str) -> str:
|
|
return " ".join(value.split())
|
|
|
|
|
|
def build(cfg: MailConfig, out: Outgoing, domain: str) -> EmailMessage:
|
|
msg = EmailMessage()
|
|
msg["From"] = formataddr((_one_line(cfg.from_name), cfg.from_address))
|
|
msg["To"] = out.recipient
|
|
msg["Subject"] = _one_line(out.subject)[:250]
|
|
msg["Date"] = format_datetime(datetime.now(UTC))
|
|
msg["Message-ID"] = make_msgid(domain=domain or None)
|
|
if out.reply_to:
|
|
msg["Reply-To"] = out.reply_to
|
|
# Abwesenheitsnotizen und Schleifen vermeiden
|
|
msg["Auto-Submitted"] = "auto-generated"
|
|
msg["X-Auto-Response-Suppress"] = "All"
|
|
for name, value in out.headers.items():
|
|
msg[name] = _one_line(value)
|
|
msg.set_content(out.text)
|
|
if out.html:
|
|
msg.add_alternative(out.html, subtype="html")
|
|
return msg
|
|
|
|
|
|
class Connection:
|
|
"""Eine Verbindung zum Relay für mehrere Mails."""
|
|
|
|
def __init__(self, cfg: MailConfig, password: str) -> None:
|
|
self.cfg = cfg
|
|
self.password = password
|
|
self.smtp: smtplib.SMTP | None = None
|
|
|
|
def __enter__(self) -> Connection:
|
|
context = ssl.create_default_context()
|
|
cfg = self.cfg
|
|
if cfg.security == "tls":
|
|
smtp: smtplib.SMTP = smtplib.SMTP_SSL(
|
|
cfg.host, cfg.port, timeout=TIMEOUT_SECONDS, context=context
|
|
)
|
|
else:
|
|
smtp = smtplib.SMTP(cfg.host, cfg.port, timeout=TIMEOUT_SECONDS)
|
|
smtp.ehlo()
|
|
if not smtp.has_extn("starttls"):
|
|
smtp.close()
|
|
raise smtplib.SMTPNotSupportedError("STARTTLS is not offered by the server")
|
|
smtp.starttls(context=context)
|
|
smtp.ehlo()
|
|
if cfg.username:
|
|
smtp.login(cfg.username, self.password)
|
|
self.smtp = smtp
|
|
return self
|
|
|
|
def send(self, msg: EmailMessage) -> None:
|
|
if self.smtp is None:
|
|
raise smtplib.SMTPServerDisconnected("not connected")
|
|
try:
|
|
refused = self.smtp.send_message(msg)
|
|
except smtplib.SMTPRecipientsRefused as exc:
|
|
codes = [code for code, _ in exc.recipients.values()]
|
|
if codes and all(code >= 500 for code in codes):
|
|
raise PermanentError(_describe(exc)) from exc
|
|
raise
|
|
except smtplib.SMTPResponseException as exc:
|
|
if exc.smtp_code >= 500:
|
|
raise PermanentError(_describe(exc)) from exc
|
|
raise
|
|
if refused:
|
|
raise PermanentError(f"recipient refused: {refused}")
|
|
|
|
def __exit__(
|
|
self,
|
|
exc_type: type[BaseException] | None,
|
|
exc: BaseException | None,
|
|
tb: TracebackType | None,
|
|
) -> None:
|
|
if self.smtp is not None:
|
|
try:
|
|
self.smtp.quit()
|
|
except (smtplib.SMTPException, OSError):
|
|
self.smtp.close()
|
|
self.smtp = None
|
|
|
|
|
|
def _describe(exc: BaseException) -> str:
|
|
"""Kurze Fehlerbeschreibung für Protokoll und Admin-Seite (ohne Passwort)."""
|
|
if isinstance(exc, smtplib.SMTPResponseException):
|
|
message = exc.smtp_error
|
|
text = message.decode("utf-8", "replace") if isinstance(message, bytes) else str(message)
|
|
return f"{exc.smtp_code} {_one_line(text)}"[:500]
|
|
if isinstance(exc, smtplib.SMTPRecipientsRefused):
|
|
parts = [f"{code} {_one_line(msg.decode('utf-8', 'replace'))}"
|
|
for code, msg in exc.recipients.values()]
|
|
return "; ".join(parts)[:500]
|
|
return f"{type(exc).__name__}: {_one_line(str(exc))}"[:500]
|
|
|
|
|
|
def describe(exc: BaseException) -> str:
|
|
return _describe(exc)
|
|
|
|
|
|
def send_now(cfg: MailConfig, password: str, out: Outgoing, domain: str) -> str | None:
|
|
"""Sofort senden (Testmail). Gibt None oder eine Fehlerbeschreibung zurück."""
|
|
try:
|
|
with Connection(cfg, password) as conn:
|
|
conn.send(build(cfg, out, domain))
|
|
except (smtplib.SMTPException, OSError, PermanentError, ValueError) as exc:
|
|
return _describe(exc)
|
|
return None
|