Each <img src="cid:NAME"> of a guest job's mail page is the file NAME next to it, attached inline (multipart/related, Content-ID <NAME>) — Proton blocks remote images but shows embedded ones. png/jpg/gif, ≤ 2 MB, ≤ 12, same containment and freshness as the page; a bad one drops the page. users/mailer.send takes images=[(name, bytes, subtype)]. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
211 lines
11 KiB
Python
211 lines
11 KiB
Python
"""
|
|
Outbound mail for the built-in login (and guest notifications): plain SMTP
|
|
submission, configured by env so the standalone container can point it at any
|
|
server.
|
|
|
|
* ``SMTP_HOST`` / ``SMTP_PORT`` (587) — unset host ⇒ mail is off: login links
|
|
can still be copied from Settings → Users.
|
|
* ``SMTP_USER`` / ``SMTP_PASS`` — submission login (skipped when empty).
|
|
* ``SMTP_FROM`` — the sender (``claude@gabvdl.xyz`` in the homelab, where the
|
|
submission endpoint is Maddy's ``mail:587`` on the shared docker network and
|
|
it DKIM-signs what it relays).
|
|
* ``SMTP_STARTTLS`` — ``1`` to upgrade the connection (off on a private
|
|
network, as the mail CLI does).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import email.message
|
|
import email.utils
|
|
import logging
|
|
import os
|
|
import smtplib
|
|
|
|
from core.i18n import msg, tr
|
|
|
|
log = logging.getLogger("ai-agent.mail")
|
|
|
|
SMTP_HOST = os.environ.get("SMTP_HOST", "")
|
|
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587") or 587)
|
|
SMTP_USER = os.environ.get("SMTP_USER", "")
|
|
SMTP_PASS = os.environ.get("SMTP_PASS", "")
|
|
SMTP_FROM = os.environ.get("SMTP_FROM", "")
|
|
# Where a guest adds a passkey at the identity provider (users/oidc.py):
|
|
# Pocket ID's account page.
|
|
IDP_ACCOUNT_URL = (os.environ.get("OIDC_ISSUER", "").strip().rstrip("/") + "/settings/account"
|
|
if os.environ.get("OIDC_ISSUER", "").strip() else "")
|
|
SMTP_STARTTLS = os.environ.get("SMTP_STARTTLS", "0") == "1"
|
|
APP_NAME = os.environ.get("APP_NAME", "ai-agent")
|
|
|
|
|
|
def enabled() -> bool:
|
|
return bool(SMTP_HOST and SMTP_FROM)
|
|
|
|
|
|
class MailError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def send(to: str, subject: str, text: str, html: str | None = None,
|
|
images: "list[tuple[str, bytes, str]] | None" = None) -> None:
|
|
"""``images``: ``(name, bytes, subtype)`` attached inline to the HTML part
|
|
(multipart/related, Content-ID ``<name>``) — what ``<img src="cid:name">``
|
|
shows, even where a mail app blocks remote images."""
|
|
if not enabled():
|
|
raise MailError("mail is not configured (SMTP_HOST / SMTP_FROM)")
|
|
msg = email.message.EmailMessage()
|
|
msg["From"] = email.utils.formataddr((APP_NAME, SMTP_FROM))
|
|
msg["To"] = to
|
|
msg["Subject"] = subject
|
|
msg["Date"] = email.utils.formatdate(localtime=True)
|
|
msg["Message-ID"] = email.utils.make_msgid(domain=SMTP_FROM.split("@")[-1])
|
|
msg["Auto-Submitted"] = "auto-generated"
|
|
msg.set_content(text)
|
|
if html:
|
|
msg.add_alternative(html, subtype="html")
|
|
if images:
|
|
part = msg.get_payload()[-1]
|
|
for name, data, sub in images:
|
|
part.add_related(data, maintype="image", subtype=sub, cid=f"<{name}>",
|
|
disposition="inline", filename=name)
|
|
try:
|
|
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=20) as s:
|
|
s.ehlo()
|
|
if SMTP_STARTTLS:
|
|
s.starttls()
|
|
s.ehlo()
|
|
if SMTP_USER and SMTP_PASS:
|
|
s.login(SMTP_USER, SMTP_PASS)
|
|
s.send_message(msg, from_addr=SMTP_FROM, to_addrs=[to])
|
|
except (smtplib.SMTPException, OSError) as exc:
|
|
log.warning("mail to %s failed: %s", to, exc)
|
|
raise MailError(f"sending failed: {exc}") from exc
|
|
|
|
|
|
def login_mail(to: str, name: str, url: str, minutes: int, lang: str = "en",
|
|
code: str = "") -> None:
|
|
"""The one-time sign-in link a guest asked for, in their language — and
|
|
its ``code``, for an app on the phone's home screen: there the link opens
|
|
in the browser, not in the app. The code leads the subject, so the mail's
|
|
notification shows it and the phone can offer to fill it in."""
|
|
hi = tr(lang, "Hi {name},", name=name)
|
|
intro = tr(lang, "Here is your sign-in link for {app}:", app=APP_NAME)
|
|
button = tr(lang, "Sign in to {app}", app=APP_NAME)
|
|
note = tr(lang, "The link works once and expires in {minutes} minutes. If you "
|
|
"didn't ask for it, ignore this mail.", minutes=minutes)
|
|
subject = button
|
|
text = f"{hi}\n\n{intro}\n\n{url}\n\n{note}\n"
|
|
code_html = ""
|
|
if code:
|
|
subject = tr(lang, "{code} is your sign-in code for {app}", code=code, app=APP_NAME)
|
|
typed = tr(lang, "In the app on your phone's home screen, type this code instead:")
|
|
note = tr(lang, "The link and the code work once and expire in {minutes} minutes. "
|
|
"If you didn't ask for them, ignore this mail.", minutes=minutes)
|
|
text = f"{hi}\n\n{intro}\n\n{url}\n\n{typed}\n\n {code}\n\n{note}\n"
|
|
code_html = (f"<p>{_esc(typed)}</p>"
|
|
f"<p style=\"font:600 28px/1.2 ui-monospace,Menlo,Consolas,monospace;"
|
|
f"letter-spacing:6px;margin:8px 0 16px\">{_esc(code)}</p>")
|
|
html = (f"<p>{_esc(hi)}</p>"
|
|
f"<p><a href=\"{_esc(url)}\" style=\"display:inline-block;padding:10px 18px;"
|
|
f"border-radius:8px;background:#6d5efc;color:#fff;text-decoration:none\">"
|
|
f"{_esc(button)}</a></p>"
|
|
f"{code_html}"
|
|
f"<p style=\"color:#666\">{_esc(note)}</p>")
|
|
send(to, subject, text, html)
|
|
|
|
|
|
def invite_mail(to: str, name: str, url: str, *, inviter: str,
|
|
projects: list[str], expires: str, home: str | None,
|
|
lang: str = "en", sso: bool = False) -> None:
|
|
"""The owner's invitation: who invited them, to what, the one-time link,
|
|
and how to sign in again later (the guest host's login page) — in the
|
|
guest's language (``expires`` comes already worded in it). ``sso``: they
|
|
sign in through the identity provider (users/oidc.py), a passkey after
|
|
this first time."""
|
|
proj = ", ".join(projects) if projects else tr(lang, "a project")
|
|
hi = tr(lang, "Hi {name},", name=name)
|
|
invited = msg("{inviter} invited you to work with Claude on {projects}.")
|
|
later = (msg("Later on, sign in at {home} with a code sent to this address — or add a "
|
|
"passkey at {account} (your phone or computer unlocks it like your screen) "
|
|
"and skip the code.") if sso else
|
|
msg("Later on, sign in at {home} with this address — a fresh link "
|
|
"is mailed to you each time."))
|
|
sign_in = tr(lang, "Sign in here (the link works once and expires in {expires}):",
|
|
expires=expires)
|
|
text = (f"{hi}\n\n{tr(lang, invited, inviter=inviter, projects=proj)}\n\n"
|
|
f"{sign_in}\n{url}\n\n{tr(lang, later, home=home, account=IDP_ACCOUNT_URL) if home else ''}\n")
|
|
# The HTML fills the same sentences with escaped (and marked-up) values.
|
|
link = f"<a href=\"{_esc(home)}\">{_esc(home)}</a>" if home else ""
|
|
html = (f"<p>{_esc(hi)}</p>"
|
|
f"<p>{tr(lang, invited, inviter=_esc(inviter), projects=f'<b>{_esc(proj)}</b>')}</p>"
|
|
f"<p><a href=\"{_esc(url)}\" style=\"display:inline-block;padding:10px 18px;"
|
|
f"border-radius:8px;background:#f97316;color:#fff;text-decoration:none\">"
|
|
f"{_esc(tr(lang, 'Accept and sign in'))}</a></p>"
|
|
f"<p style=\"color:#666\">"
|
|
f"{tr(lang, 'The link works once and expires in {expires}.', expires=_esc(expires))}"
|
|
+ (" " + tr(lang, later, home=link, account=IDP_ACCOUNT_URL) if home else "")
|
|
+ "</p>")
|
|
send(to, tr(lang, "{inviter} invited you to {app}", inviter=inviter, app=APP_NAME),
|
|
text, html)
|
|
|
|
|
|
def moved_mail(to: str, name: str, url: str, *, home: str, expires: str,
|
|
lang: str = "en") -> None:
|
|
"""The guest surface moved to ``home``: a fresh sign-in link there (``url``,
|
|
an invitation-length one), and how to put the app back on the phone's
|
|
home screen — the old icon points at the old address, which only
|
|
redirects now, signed out."""
|
|
hi = tr(lang, "Hi {name},", name=name)
|
|
moved = msg("{app} has a new address: {home}. The old one now sends you there, "
|
|
"signed out.")
|
|
sign_in = tr(lang, "Sign in at the new address (the link works once and expires "
|
|
"in {expires}):", expires=expires)
|
|
phone = tr(lang, "On your phone, add it to the home screen again from the new "
|
|
"address — iPhone: Safari → Share → Add to Home Screen; Android: "
|
|
"Chrome → ⋮ → Add to Home screen — and delete the old icon.")
|
|
code = tr(lang, "From now on, each sign-in mail also carries a 6-digit code: type it "
|
|
"in the app on your home screen.")
|
|
text = (f"{hi}\n\n{tr(lang, moved, app=APP_NAME, home=home)}\n\n{sign_in}\n{url}\n\n"
|
|
f"{phone}\n\n{code}\n")
|
|
link = f"<a href=\"{_esc(home)}\">{_esc(home)}</a>"
|
|
html = (f"<p>{_esc(hi)}</p>"
|
|
f"<p>{tr(lang, moved, app=_esc(APP_NAME), home=link)}</p>"
|
|
f"<p>{_esc(sign_in)}</p>"
|
|
f"<p><a href=\"{_esc(url)}\" style=\"display:inline-block;padding:10px 18px;"
|
|
f"border-radius:8px;background:#f97316;color:#fff;text-decoration:none\">"
|
|
f"{_esc(tr(lang, 'Sign in at the new address'))}</a></p>"
|
|
f"<p>{_esc(phone)}</p>"
|
|
f"<p style=\"color:#666\">{_esc(code)}</p>")
|
|
send(to, tr(lang, "{app} has a new address", app=APP_NAME), text, html)
|
|
|
|
|
|
def sso_mail(to: str, name: str, url: str, *, home: str, apps: list[dict],
|
|
expires: str, lang: str = "en") -> None:
|
|
"""Sign-in moved to the identity provider (users/oidc.py): one account for
|
|
the ai-agent and the other apps they have (``apps``: ``{label, url}``),
|
|
a link that signs them in once (an invitation-length login code), then a
|
|
passkey — or a code by mail — from the sign-in page."""
|
|
hi = tr(lang, "Hi {name},", name=name)
|
|
others = ", ".join(f"{a['label']} ({a['url']})" if a.get("url") else a["label"]
|
|
for a in apps)
|
|
one = (tr(lang, "{app} has a new sign-in: one account for {app} and {others}.",
|
|
app=APP_NAME, others=others) if others else
|
|
tr(lang, "{app} has a new sign-in.", app=APP_NAME))
|
|
how = tr(lang, "This link signs you in once (it expires in {expires}).", expires=expires)
|
|
later = tr(lang, "Later on, sign in at {home} with a code sent to this address — or add a "
|
|
"passkey at {account} (your phone or computer unlocks it like your screen) "
|
|
"and skip the code.", home=home, account=IDP_ACCOUNT_URL)
|
|
text = f"{hi}\n\n{one}\n\n{how}\n{url}\n\n{later}\n"
|
|
html = (f"<p>{_esc(hi)}</p><p>{_esc(one)}</p><p>{_esc(how)}</p>"
|
|
f"<p><a href=\"{_esc(url)}\" style=\"display:inline-block;padding:10px 18px;"
|
|
f"border-radius:8px;background:#f97316;color:#fff;text-decoration:none\">"
|
|
f"{_esc(tr(lang, 'Sign in'))}</a></p>"
|
|
f"<p style=\"color:#666\">{_esc(later)}</p>")
|
|
send(to, tr(lang, "One account for {app} and your other apps", app=APP_NAME)
|
|
if others else tr(lang, "{app} has a new sign-in", app=APP_NAME), text, html)
|
|
|
|
|
|
def _esc(s: str) -> str:
|
|
return (s or "").replace("&", "&").replace("<", "<") \
|
|
.replace(">", ">").replace('"', """)
|