# -*- coding: utf-8 -*- """邮件服务:优先 Resend API,旧 SMTP 配置作为回退。 配置(环境变量): PL_RESEND_API_KEY Resend API Key(re_xxx),配置后优先走 Resend PL_MAIL_FROM 统一发件地址,默认 mail@steadypackaging.com PL_MAIL_FROM_NAME 发件人名称,默认 Steady PL_SMTP_HOST/PORT/USER/PASSWORD/FROM(未配置 Resend 时的回退通道) 两者都未配置时进入存档模式:邮件不真实发出, 内容写入订单消息线程(email_status=archived),管理员可复制到任意渠道发送。 注意:Resend 要求发件域名(steadypackaging.com)已在 Resend 后台完成 DNS 验证(SPF/DKIM),否则 API 返回 403 domain_not_verified。 """ import html as html_lib import json import os import smtplib import urllib.error import urllib.request from email.header import Header from email.mime.text import MIMEText from email.utils import formataddr RESEND_API = "https://api.resend.com/emails" DEFAULT_FROM = "mail@steadypackaging.com" DEFAULT_FROM_NAME = "Steady" def _from_addr() -> str: return os.environ.get("PL_MAIL_FROM", "").strip() or DEFAULT_FROM def _from_header() -> str: """Resend JSON API 直接吃 UTF-8,不能用 SMTP 的 RFC2047 编码(会 403 1010)。""" name = os.environ.get("PL_MAIL_FROM_NAME", DEFAULT_FROM_NAME) return "%s <%s>" % (name, _from_addr()) def smtp_configured() -> bool: """是否已配置真实发信渠道(Resend 或 SMTP)。保留旧函数名,调用方语义不变。""" return bool(os.environ.get("PL_RESEND_API_KEY") or os.environ.get("PL_SMTP_HOST")) def send_email(to: str, subject: str, body: str, html: str | None = None) -> tuple: """返回 (status, error):status = sent | archived。 body 为纯文本正文;html 可选(品牌模板),缺省时由纯文本转义生成。 """ if os.environ.get("PL_RESEND_API_KEY"): return _send_via_resend(to, subject, body, html) if os.environ.get("PL_SMTP_HOST"): return _send_via_smtp(to, subject, body, html) return "archived", None def _fallback_html(body: str) -> str: return ( '
' + html_lib.escape(body).replace("\n", "
\n") + "
" ) def _send_via_resend(to: str, subject: str, body: str, html: str | None = None) -> tuple: payload = { "from": _from_header(), "to": [to], "subject": subject, "text": body, "html": html or _fallback_html(body), } req = urllib.request.Request( RESEND_API, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers={ "Authorization": "Bearer " + os.environ["PL_RESEND_API_KEY"].strip(), "Content-Type": "application/json", # Resend 前置的 Cloudflare 会拦截默认 UA Python-urllib/x(403 1010) "User-Agent": "pouchlab-mailer/1.0", }, method="POST", ) try: with urllib.request.urlopen(req, timeout=15) as resp: if 200 <= resp.status < 300: return "sent", None return "archived", "Resend HTTP %s" % resp.status except urllib.error.HTTPError as e: detail = e.read().decode("utf-8", "replace")[:500] return "archived", "Resend %s: %s" % (e.code, detail) except Exception as e: # noqa: BLE001 — 网络/超时等失败都归档并带回原因 return "archived", str(e) def _send_via_smtp(to: str, subject: str, body: str, html: str | None = None) -> tuple: from email.mime.multipart import MIMEMultipart host = os.environ["PL_SMTP_HOST"] port = int(os.environ.get("PL_SMTP_PORT", "465")) user = os.environ.get("PL_SMTP_USER", "") password = os.environ.get("PL_SMTP_PASSWORD", "") from_addr = os.environ.get("PL_SMTP_FROM") or _from_addr() use_ssl = os.environ.get("PL_SMTP_SSL", "1") == "1" try: if html: msg = MIMEMultipart("alternative") msg.attach(MIMEText(body, "plain", "utf-8")) msg.attach(MIMEText(html, "html", "utf-8")) else: msg = MIMEText(body, "plain", "utf-8") msg["Subject"] = Header(subject, "utf-8") msg["From"] = formataddr((str(Header(DEFAULT_FROM_NAME, "utf-8")), from_addr)) msg["To"] = to if use_ssl: server = smtplib.SMTP_SSL(host, port, timeout=15) else: server = smtplib.SMTP(host, port, timeout=15) server.starttls() try: if user: server.login(user, password) server.sendmail(from_addr, [to], msg.as_string()) finally: server.quit() return "sent", None except Exception as e: # noqa: BLE001 — SMTP 各类失败都归档并带回原因 return "archived", str(e)