emailer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. """Programmatic email (Mode B) via stdlib smtplib/imaplib - no human in the loop.
  2. This is what turns email opt-outs autonomous: `send()` delivers the rendered
  3. request straight to the broker's known opt-out address, and `find_verification_link()`
  4. polls the inbox for the broker's confirmation email and extracts the link (scored
  5. by email_modes.extract_verification_link, so arbitrary/phishing links are ignored).
  6. The agent still OPENS the link with its own browser - several brokers bind the
  7. verification session to the browser that opens it (see the intelius record).
  8. Configuration comes from the same env vars the Hermes email gateway uses:
  9. EMAIL_ADDRESS / EMAIL_PASSWORD (required for Mode B)
  10. EMAIL_SMTP_HOST / EMAIL_SMTP_PORT (optional; inferred for common providers)
  11. EMAIL_IMAP_HOST / EMAIL_IMAP_PORT (optional; inferred for common providers)
  12. Anti-misuse: `send()` refuses a recipient that is not the broker record's own
  13. opt-out/privacy address - this module cannot be repurposed to email arbitrary people.
  14. All network calls live behind small functions that the hermetic tests monkeypatch.
  15. """
  16. from __future__ import annotations
  17. import email as _email
  18. import email.utils
  19. import imaplib
  20. import json
  21. import os
  22. import re
  23. import smtplib
  24. import time
  25. from email.message import EmailMessage
  26. from pathlib import Path
  27. import email_modes
  28. import paths
  29. # provider domain -> (smtp_host, smtp_port, imap_host, imap_port)
  30. PROVIDERS = {
  31. "gmail.com": ("smtp.gmail.com", 587, "imap.gmail.com", 993),
  32. "googlemail.com": ("smtp.gmail.com", 587, "imap.gmail.com", 993),
  33. "outlook.com": ("smtp-mail.outlook.com", 587, "outlook.office365.com", 993),
  34. "hotmail.com": ("smtp-mail.outlook.com", 587, "outlook.office365.com", 993),
  35. "live.com": ("smtp-mail.outlook.com", 587, "outlook.office365.com", 993),
  36. "yahoo.com": ("smtp.mail.yahoo.com", 587, "imap.mail.yahoo.com", 993),
  37. "icloud.com": ("smtp.mail.me.com", 587, "imap.mail.me.com", 993),
  38. "me.com": ("smtp.mail.me.com", 587, "imap.mail.me.com", 993),
  39. "fastmail.com": ("smtp.fastmail.com", 587, "imap.fastmail.com", 993),
  40. }
  41. def _domain(address: str) -> str:
  42. return address.rsplit("@", 1)[-1].lower() if "@" in address else ""
  43. def smtp_settings(env: dict | None = None) -> dict | None:
  44. """SMTP connection settings, or None when sending is not configured."""
  45. env = os.environ if env is None else env
  46. address, password = env.get("EMAIL_ADDRESS"), env.get("EMAIL_PASSWORD")
  47. if not (address and password):
  48. return None
  49. inferred = PROVIDERS.get(_domain(address))
  50. host = env.get("EMAIL_SMTP_HOST") or (inferred[0] if inferred else None)
  51. if not host:
  52. return None # unknown provider and no explicit host
  53. port = int(env.get("EMAIL_SMTP_PORT") or (inferred[1] if inferred else 587))
  54. return {"host": host, "port": port, "address": address, "password": password}
  55. def imap_settings(env: dict | None = None) -> dict | None:
  56. """IMAP connection settings, or None when inbox reading is not configured."""
  57. env = os.environ if env is None else env
  58. address, password = env.get("EMAIL_ADDRESS"), env.get("EMAIL_PASSWORD")
  59. if not (address and password):
  60. return None
  61. inferred = PROVIDERS.get(_domain(address))
  62. host = env.get("EMAIL_IMAP_HOST") or (inferred[2] if inferred else None)
  63. if not host:
  64. return None
  65. port = int(env.get("EMAIL_IMAP_PORT") or (inferred[3] if inferred else 993))
  66. return {"host": host, "port": port, "address": address, "password": password}
  67. def available(env: dict | None = None) -> dict:
  68. return {"smtp": smtp_settings(env) is not None, "imap": imap_settings(env) is not None}
  69. # --- sending ------------------------------------------------------------------
  70. def broker_addresses(broker: dict) -> list[str]:
  71. """Every address the broker record itself declares (the ONLY valid recipients).
  72. Includes the primary opt-out email, the right-to-delete lane's email
  73. (optout.deletion.email), and any mailto: links parsed from BADBOOL.
  74. """
  75. opt = broker.get("optout") or {}
  76. out = [a for a in [opt.get("email"), (opt.get("deletion") or {}).get("email")] if a]
  77. for link in opt.get("links") or []:
  78. url = (link.get("url") or "")
  79. if url.lower().startswith("mailto:"):
  80. out.append(url[7:].split("?")[0])
  81. seen: set[str] = set()
  82. deduped = []
  83. for a in out:
  84. if a.lower() not in seen:
  85. seen.add(a.lower())
  86. deduped.append(a)
  87. return deduped
  88. def _split_subject_body(text: str) -> tuple[str, str]:
  89. """Templates start with a 'Subject: ...' line; split it out for the MIME header."""
  90. lines = text.splitlines()
  91. if lines and lines[0].lower().startswith("subject:"):
  92. return lines[0].split(":", 1)[1].strip(), "\n".join(lines[1:]).lstrip("\n")
  93. return "Data removal request", text
  94. def browser_send_payload(broker: dict, body_text: str, to: str | None = None) -> dict:
  95. """Build a recipient-locked {to, subject, body} for the agent to send via browser webmail.
  96. No network and no credentials: the deterministic part (recipient-lock to the broker's own
  97. declared address, subject/body split) happens here; the agent then composes and sends it in
  98. the operator's logged-in webmail with browser_exec. Same recipient guard as `send()`, so
  99. the browser lane cannot be pointed at an arbitrary person either.
  100. """
  101. allowed = broker_addresses(broker)
  102. if not allowed:
  103. raise RuntimeError(f"broker {broker.get('id')!r} declares no opt-out email address")
  104. recipient = to or allowed[0]
  105. if recipient.lower() not in {a.lower() for a in allowed}:
  106. raise PermissionError(
  107. f"refusing to target {recipient!r}: not an address the broker record declares "
  108. f"(allowed: {allowed})"
  109. )
  110. subject, body = _split_subject_body(body_text)
  111. return {"to": recipient, "subject": subject, "body": body}
  112. def _rate_limit_path() -> Path:
  113. return paths.data_dir() / "email-rate.json"
  114. def _respect_rate_limit(min_interval: float, sleep, now, state_path=None) -> None:
  115. """Pace sends across CLI invocations so a run can't torch the sending account.
  116. Persists the last-send wall-clock time; if the next send is too soon, sleep the
  117. remainder. Cross-process because each `send-email` is a separate invocation.
  118. """
  119. if min_interval <= 0:
  120. return
  121. p = state_path or _rate_limit_path()
  122. last = 0.0
  123. try:
  124. last = float(json.loads(p.read_text(encoding="utf-8")).get("last", 0.0))
  125. except (OSError, ValueError, TypeError):
  126. last = 0.0
  127. wait = min_interval - (now() - last)
  128. if wait > 0:
  129. sleep(min(wait, min_interval))
  130. try:
  131. p.parent.mkdir(parents=True, exist_ok=True)
  132. p.write_text(json.dumps({"last": now()}), encoding="utf-8")
  133. except OSError:
  134. pass
  135. # SMTP errors that are permanent (don't retry) vs transient (retry with backoff).
  136. _SMTP_PERMANENT = (smtplib.SMTPAuthenticationError, smtplib.SMTPRecipientsRefused,
  137. smtplib.SMTPSenderRefused, smtplib.SMTPDataError)
  138. def send(broker: dict, body_text: str, to: str | None = None,
  139. env: dict | None = None, _smtp_factory=None,
  140. min_interval: float = 0.0, max_retries: int = 3,
  141. _sleep=time.sleep, _now=time.time, _rate_state=None) -> dict:
  142. """Send an opt-out/legal request to the broker's own opt-out address.
  143. Recipient is locked to an address the broker record declares (PermissionError
  144. otherwise). `min_interval` paces sends across invocations (deliverability /
  145. account-safety); transient SMTP/socket failures retry with exponential backoff,
  146. permanent ones (auth, recipient refused) raise immediately. NOTE: a successful
  147. SMTP handoff is NOT proof of delivery - real bounces arrive later as inbound mail;
  148. in programmatic mode `poll-verification`/inbox review surfaces them, and the
  149. due-queue re-scan is the true confirmation. Returns send metadata.
  150. """
  151. settings = smtp_settings(env)
  152. if not settings:
  153. raise RuntimeError(
  154. "programmatic email not configured (need EMAIL_ADDRESS + EMAIL_PASSWORD, and "
  155. "EMAIL_SMTP_HOST for non-mainstream providers); fall back to `render-email` drafts"
  156. )
  157. allowed = broker_addresses(broker)
  158. if not allowed:
  159. raise RuntimeError(f"broker {broker.get('id')!r} declares no opt-out email address")
  160. recipient = to or allowed[0]
  161. if recipient.lower() not in {a.lower() for a in allowed}:
  162. raise PermissionError(
  163. f"refusing to send to {recipient!r}: not an address the broker record declares "
  164. f"(allowed: {allowed})"
  165. )
  166. subject, body = _split_subject_body(body_text)
  167. msg = EmailMessage()
  168. msg["From"] = settings["address"]
  169. msg["To"] = recipient
  170. msg["Subject"] = subject
  171. msg["Date"] = email.utils.formatdate(localtime=True)
  172. msg["Message-ID"] = email.utils.make_msgid()
  173. msg.set_content(body)
  174. _respect_rate_limit(min_interval, _sleep, _now, _rate_state)
  175. factory = _smtp_factory or smtplib.SMTP
  176. attempts = 0
  177. while True:
  178. attempts += 1
  179. try:
  180. with factory(settings["host"], settings["port"], timeout=30) as smtp:
  181. smtp.ehlo()
  182. try:
  183. smtp.starttls()
  184. smtp.ehlo()
  185. except smtplib.SMTPNotSupportedError:
  186. pass # already-TLS ports / test doubles
  187. smtp.login(settings["address"], settings["password"])
  188. smtp.send_message(msg)
  189. break
  190. except _SMTP_PERMANENT:
  191. raise # auth / recipient refused: retrying won't help
  192. except (smtplib.SMTPException, OSError) as exc:
  193. if attempts > max_retries:
  194. raise RuntimeError(f"SMTP send failed after {attempts} attempts: {exc}") from exc
  195. _sleep(min(2 ** (attempts - 1), 30)) # 1s, 2s, 4s... capped
  196. return {"to": recipient, "subject": subject, "message_id": msg["Message-ID"],
  197. "from": settings["address"], "attempts": attempts,
  198. "delivery_note": "SMTP accepted; not proof of delivery - a bounce would arrive as "
  199. "inbound mail. The due-queue re-scan is the real confirmation."}
  200. # --- inbox polling ------------------------------------------------------------
  201. def _decode_part(part) -> str:
  202. try:
  203. payload = part.get_payload(decode=True)
  204. if payload is None:
  205. return ""
  206. charset = part.get_content_charset() or "utf-8"
  207. return payload.decode(charset, errors="replace")
  208. except Exception:
  209. return ""
  210. def message_text(msg) -> str:
  211. """All text/plain + text/html content of a parsed email message."""
  212. chunks: list[str] = []
  213. if msg.is_multipart():
  214. for part in msg.walk():
  215. if part.get_content_type() in ("text/plain", "text/html"):
  216. chunks.append(_decode_part(part))
  217. else:
  218. chunks.append(_decode_part(msg))
  219. return "\n".join(c for c in chunks if c)
  220. def _broker_domains(broker: dict) -> list[str]:
  221. """Domains this broker legitimately mails from (site domains + optout email domain)."""
  222. domains: list[str] = []
  223. for section in ("optout", "search"):
  224. url = ((broker.get(section) or {}).get("url")) or ""
  225. m = re.search(r"https?://([^/]+)", url)
  226. if m:
  227. domains.append(m.group(1).lower().removeprefix("www."))
  228. opt_email = (broker.get("optout") or {}).get("email")
  229. if opt_email and "@" in opt_email:
  230. domains.append(_domain(opt_email))
  231. # strip subdomains to the registrable-ish tail (mailer.intelius.com -> intelius.com)
  232. tails = {".".join(d.split(".")[-2:]) for d in domains if d}
  233. return sorted(tails)
  234. def fetch_recent(env: dict | None = None, since_days: int = 3, limit: int = 30,
  235. _imap_factory=None) -> list[dict]:
  236. """Fetch recent inbox messages: [{from, subject, date, text}], newest first."""
  237. settings = imap_settings(env)
  238. if not settings:
  239. raise RuntimeError("IMAP not configured (need EMAIL_ADDRESS + EMAIL_PASSWORD, and "
  240. "EMAIL_IMAP_HOST for non-mainstream providers)")
  241. import datetime as _dt
  242. since = (_dt.date.today() - _dt.timedelta(days=max(0, since_days))).strftime("%d-%b-%Y")
  243. factory = _imap_factory or imaplib.IMAP4_SSL
  244. conn = factory(settings["host"], settings["port"])
  245. try:
  246. conn.login(settings["address"], settings["password"])
  247. conn.select("INBOX", readonly=True)
  248. _typ, data = conn.search(None, "SINCE", since)
  249. ids = (data[0].split() if data and data[0] else [])[-limit:]
  250. out: list[dict] = []
  251. for mid in reversed(ids): # newest first
  252. _typ, msg_data = conn.fetch(mid, "(RFC822)")
  253. raw = next((p[1] for p in msg_data or [] if isinstance(p, tuple)), None)
  254. if not raw:
  255. continue
  256. msg = _email.message_from_bytes(raw)
  257. out.append({
  258. "from": msg.get("From", ""),
  259. "subject": msg.get("Subject", ""),
  260. "date": msg.get("Date", ""),
  261. "text": message_text(msg),
  262. })
  263. return out
  264. finally:
  265. try:
  266. conn.logout()
  267. except Exception:
  268. pass
  269. def link_from_messages(messages: list[dict], broker: dict) -> dict | None:
  270. """Pure: find the broker's verification link in already-fetched messages.
  271. A message is only considered if its From domain OR any contained link matches
  272. the broker's own domains; the link itself must pass the anti-phishing scorer.
  273. """
  274. domains = _broker_domains(broker)
  275. for m in messages:
  276. sender = (m.get("from") or "").lower()
  277. text = m.get("text") or ""
  278. sender_match = any(d in sender for d in domains)
  279. body_match = any(d in text.lower() for d in domains)
  280. if not (sender_match or body_match):
  281. continue
  282. link = email_modes.extract_verification_link(text, broker)
  283. if link:
  284. return {"link": link, "from": m.get("from"), "subject": m.get("subject"),
  285. "date": m.get("date")}
  286. return None
  287. def find_verification_link(broker: dict, env: dict | None = None, since_days: int = 3,
  288. _imap_factory=None) -> dict | None:
  289. """Poll the inbox and return the broker's verification link (or None yet)."""
  290. messages = fetch_recent(env, since_days=since_days, _imap_factory=_imap_factory)
  291. return link_from_messages(messages, broker)