Content-filter-ai / notify.py
Pabot's picture
Upload 4 files
79ebb0d verified
Raw History Blame Contribute Delete
3.01 kB
"""Send the 'your report is ready' email via Resend (no-op if not configured).
Mirrors the Render backend sender, including the User-Agent header that keeps
Cloudflare (in front of the Resend API) from rejecting the default agent (1010).
"""
from __future__ import annotations
import json
import logging
import os
import urllib.error
import urllib.request
log = logging.getLogger("worker.notify")
RESEND_API_KEY = os.environ.get("RESEND_API_KEY", "")
def _with_display_name(sender: str) -> str:
"""Ensure the From has a display name, else Gmail shows the bare address twice."""
sender = sender.strip().strip('"').strip("'").strip()
return sender if "<" in sender else f"Content Filter AI <{sender}>"
RESEND_FROM = _with_display_name(os.environ.get("RESEND_FROM", "Content Filter AI <onboarding@resend.dev>"))
APP_URL = os.environ.get("APP_URL", "https://contentfilter.ai").rstrip("/")
def send_report_ready_email(to: str, filename: str) -> None:
if not RESEND_API_KEY or not to:
log.warning("notify skipped: has_key=%s to=%r", bool(RESEND_API_KEY), to)
return
html = (
f'<div style="font-family:Arial,sans-serif;background:#070b11;color:#eaf3ee;'
f'padding:32px;border-radius:14px;max-width:520px;margin:auto">'
f'<h1 style="color:#34e89e;font-size:22px;margin:0 0 12px">Your report is ready</h1>'
f'<p style="color:#869a91;font-size:15px;line-height:1.6;margin:0 0 20px">'
f'Good news, the scan for <strong style="color:#eaf3ee">{filename}</strong> is complete. '
f'Your monetization risk report is ready to view.</p>'
f'<a href="{APP_URL}/dashboard#history" style="display:inline-block;background:#14b57c;color:#fff;'
f'font-weight:600;text-decoration:none;padding:12px 22px;border-radius:999px">View my report</a>'
f'<p style="color:#869a91;font-size:12px;margin-top:24px">Content Filter AI</p></div>'
)
payload = json.dumps({
"from": RESEND_FROM,
"to": [to],
"subject": "The process is complete, your report is ready",
"html": html,
}).encode()
req = urllib.request.Request(
"https://api.resend.com/emails",
data=payload,
headers={
"Authorization": f"Bearer {RESEND_API_KEY}",
"Content-Type": "application/json",
"User-Agent": "content-filter-ai/1.0 (+https://contentfilter.ai)",
"Accept": "application/json",
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=15) as resp:
log.info("Resend email sent to %s (status %s)", to, resp.status)
except urllib.error.HTTPError as exc: # noqa: BLE001
detail = ""
try:
detail = exc.read().decode("utf-8", "ignore")
except Exception: # noqa: BLE001
pass
log.warning("Resend email failed (%s): %s", exc.code, detail)
except Exception as exc: # noqa: BLE001
log.warning("Resend email failed: %s", exc)