feat(email): each account gets its own email, in its own zone (milestone 495)
CI / lint (push) Successful in 3s
CI / integration (push) Successful in 1m0s
CI / unit (push) Successful in 1m24s
CI / publish (push) Successful in 1m32s

Milestone 495 "Email goes to each account, in its own time zone", on the
operator's ruling (System 156): notifications go to each user, times in
their zone, defaults on, toggled per user or per role.

- users.notify_alerts / notify_report (migration 0036): None follows the
  role's default, notify.<kind>.<role> in settings, all on to start.
- mail.pick_recipients: active accounts that want the email and have an
  address mail can reach (an SSO placeholder like name@oidc is skipped and
  flagged), each in its own zone with no UTC beside it, then the Also send
  to addresses in their chosen zone with UTC beside. One copy per address,
  all over one SMTP connection.
- Alerts, the weekly report and the test email (to you, in your zone, plus
  the typed addresses) send that way. The save-time smtp.tz capture is gone.
- Notifications: a role × email table of defaults, who each email reaches
  and who can't be reached, and Also send to with its own zone, which starts
  as the first admin's to open the page.
- Account page: your address and your two switches. Users: an Emailed
  column, and an admin sets an account's switches on its page.
- The Alerts page counts the accounts it emails. zone_select macro and
  formatting.zones_by_region shared by Account and Notifications.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 15:16:17 -04:00
co-authored by Claude Opus 5.5
parent c533eec33a
commit 22090b02d8
27 changed files with 601 additions and 132 deletions
+13 -15
View File
@@ -4,7 +4,6 @@ Weekly digest report: uptime, active alerts, alert events, top metrics.
Called by the scheduler (hourly check) or triggered manually from Settings.
"""
from __future__ import annotations
import asyncio
import logging
from datetime import datetime, timedelta, timezone
@@ -12,7 +11,7 @@ from sqlalchemy import and_, case, func, select
from steward.alerts import service as alert_svc
from steward.core.formatting import zone
from steward.core.mail import message, report_email
from steward.core.mail import message, recipients, report_email, send
from steward.core.settings import get_setting
from steward.models.alerts import AlertEvent
from steward.models.metrics import PluginMetric
@@ -118,10 +117,16 @@ async def build_report_data(app) -> dict:
async def send_report(app) -> tuple[bool, str]:
"""Build and email the weekly digest. Returns (success, message)."""
"""Email the weekly digest to each account that gets it, and the "Also
send to" addresses, each in its own zone. Returns (success, message)."""
smtp_cfg = app.config.get("SMTP", {})
if not smtp_cfg.get("host") or not smtp_cfg.get("recipients"):
return False, "SMTP not configured — set host and recipients in Settings → Notifications."
if not smtp_cfg.get("host"):
return False, "No mail server is set. Set one in Settings → Notifications."
async with app.db_sessionmaker() as db:
to = await recipients(db, "report", smtp_cfg)
if not to:
return False, ("Nobody gets the weekly report: no account has it on with a real email "
"address, and there are no Also send to addresses.")
try:
data = await build_report_data(app)
@@ -129,20 +134,13 @@ async def send_report(app) -> tuple[bool, str]:
logger.exception("Failed to build report data")
return False, f"Data collection failed: {exc}"
async with app.db_sessionmaker() as db:
tz = zone(await get_setting(db, "reports.schedule_tz"))
subject, text, html = report_email(smtp_cfg, data, tz)
msg = message(smtp_cfg, subject, text, html)
try:
loop = asyncio.get_running_loop()
from steward.core.notifications import _smtp_send_sync
await loop.run_in_executor(None, _smtp_send_sync, smtp_cfg, msg)
logger.info("Weekly report sent to %s", smtp_cfg["recipients"])
return True, f"Report sent to {', '.join(smtp_cfg['recipients'])}."
await send(smtp_cfg, [message(smtp_cfg, r.address, *report_email(smtp_cfg, data, r)) for r in to])
except Exception as exc:
logger.error("Failed to send weekly report: %s", exc)
return False, f"Send failed: {exc}"
logger.info("Weekly report sent to %d address(es)", len(to))
return True, f"Report sent to {', '.join(r.address for r in to)}."
def report_due(now: datetime, day: int, hour: int, tz) -> bool: