feat(email): every email is a row in email_outbox until the server accepts it (#5506)
#5506 "Email outbox: a table of outgoing email and a sender that retries until accepted, for up to an hour" (milestone 501). - email_outbox (migration 0042) holds each message per recipient, its words, its state (held / pending / sending / sent / failed), attempts and the server's last answer. email_outbox_events links alert events for #5507. - core/outbox.py: enqueue; a sender task every 15 s claims what is due (SKIP LOCKED, stale claims released), sends the batch over one connection with no session held, and settles each row: - accepted -> sent; - a 5xx refusal -> failed at once with the server's words; - no connection, a timeout, a 4xx -> retried after 30 s, 1, 2, 5, 10, 15 min, the last try at the hour, then failed; - a test (retry=False) settles on its first answer. It runs on startup, so a row left by a restart goes out at boot. - notifications.smtp_open is the one place a connection is opened. - mail.message takes the html part as optional. - cleanup ages email_outbox rows on the data window. Senders move onto it in #5507 and #5508. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -55,7 +55,9 @@ async def _send_email(cfg: dict, alert: dict, recipients: list) -> dict:
|
||||
return {"sent": False, "error": str(exc)}
|
||||
|
||||
|
||||
def _smtp_send_sync(cfg: dict, messages: list[EmailMessage]) -> None:
|
||||
def smtp_open(cfg: dict) -> smtplib.SMTP:
|
||||
"""A connection to the mail server, TLS and login done, every step
|
||||
bounded by SMTP_TIMEOUT_S. The caller closes it (use it in `with`)."""
|
||||
port = int(cfg.get("port") or 587)
|
||||
mode = smtp_mode(port, cfg.get("tls", True))
|
||||
ctx = ssl.create_default_context()
|
||||
@@ -63,11 +65,19 @@ def _smtp_send_sync(cfg: dict, messages: list[EmailMessage]) -> None:
|
||||
smtp = smtplib.SMTP_SSL(cfg["host"], port, timeout=SMTP_TIMEOUT_S, context=ctx)
|
||||
else:
|
||||
smtp = smtplib.SMTP(cfg["host"], port, timeout=SMTP_TIMEOUT_S)
|
||||
with smtp:
|
||||
try:
|
||||
if mode == "starttls":
|
||||
smtp.starttls(context=ctx)
|
||||
if cfg.get("username"):
|
||||
smtp.login(cfg["username"], cfg.get("password", ""))
|
||||
except BaseException:
|
||||
smtp.close()
|
||||
raise
|
||||
return smtp
|
||||
|
||||
|
||||
def _smtp_send_sync(cfg: dict, messages: list[EmailMessage]) -> None:
|
||||
with smtp_open(cfg) as smtp:
|
||||
for msg in messages:
|
||||
smtp.send_message(msg)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user