email_service.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. # -*- coding: utf-8 -*-
  2. """邮件服务:优先 Resend API,旧 SMTP 配置作为回退。
  3. 配置(环境变量):
  4. PL_RESEND_API_KEY Resend API Key(re_xxx),配置后优先走 Resend
  5. PL_MAIL_FROM 统一发件地址,默认 mail@steadypackaging.com
  6. PL_MAIL_FROM_NAME 发件人名称,默认 袋研社 POUCHLAB
  7. PL_SMTP_HOST/PORT/USER/PASSWORD/FROM(未配置 Resend 时的回退通道)
  8. 两者都未配置时进入存档模式:邮件不真实发出,
  9. 内容写入订单消息线程(email_status=archived),管理员可复制到任意渠道发送。
  10. 注意:Resend 要求发件域名(steadypackaging.com)已在 Resend 后台完成
  11. DNS 验证(SPF/DKIM),否则 API 返回 403 domain_not_verified。
  12. """
  13. import html as html_lib
  14. import json
  15. import os
  16. import smtplib
  17. import urllib.error
  18. import urllib.request
  19. from email.header import Header
  20. from email.mime.text import MIMEText
  21. from email.utils import formataddr
  22. RESEND_API = "https://api.resend.com/emails"
  23. DEFAULT_FROM = "mail@steadypackaging.com"
  24. DEFAULT_FROM_NAME = "Steady"
  25. def _from_addr() -> str:
  26. return os.environ.get("PL_MAIL_FROM", "").strip() or DEFAULT_FROM
  27. def _from_header() -> str:
  28. """Resend JSON API 直接吃 UTF-8,不能用 SMTP 的 RFC2047 编码(会 403 1010)。"""
  29. name = os.environ.get("PL_MAIL_FROM_NAME", DEFAULT_FROM_NAME)
  30. return "%s <%s>" % (name, _from_addr())
  31. def smtp_configured() -> bool:
  32. """是否已配置真实发信渠道(Resend 或 SMTP)。保留旧函数名,调用方语义不变。"""
  33. return bool(os.environ.get("PL_RESEND_API_KEY") or os.environ.get("PL_SMTP_HOST"))
  34. def send_email(to: str, subject: str, body: str, html: str | None = None) -> tuple:
  35. """返回 (status, error):status = sent | archived。
  36. body 为纯文本正文;html 可选(品牌模板),缺省时由纯文本转义生成。
  37. """
  38. if os.environ.get("PL_RESEND_API_KEY"):
  39. return _send_via_resend(to, subject, body, html)
  40. if os.environ.get("PL_SMTP_HOST"):
  41. return _send_via_smtp(to, subject, body, html)
  42. return "archived", None
  43. def _fallback_html(body: str) -> str:
  44. return (
  45. '<div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;'
  46. 'line-height:1.7;color:#222">'
  47. + html_lib.escape(body).replace("\n", "<br>\n")
  48. + "</div>"
  49. )
  50. def _send_via_resend(to: str, subject: str, body: str, html: str | None = None) -> tuple:
  51. payload = {
  52. "from": _from_header(),
  53. "to": [to],
  54. "subject": subject,
  55. "text": body,
  56. "html": html or _fallback_html(body),
  57. }
  58. req = urllib.request.Request(
  59. RESEND_API,
  60. data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
  61. headers={
  62. "Authorization": "Bearer " + os.environ["PL_RESEND_API_KEY"].strip(),
  63. "Content-Type": "application/json",
  64. # Resend 前置的 Cloudflare 会拦截默认 UA Python-urllib/x(403 1010)
  65. "User-Agent": "pouchlab-mailer/1.0",
  66. },
  67. method="POST",
  68. )
  69. try:
  70. with urllib.request.urlopen(req, timeout=15) as resp:
  71. if 200 <= resp.status < 300:
  72. return "sent", None
  73. return "archived", "Resend HTTP %s" % resp.status
  74. except urllib.error.HTTPError as e:
  75. detail = e.read().decode("utf-8", "replace")[:500]
  76. return "archived", "Resend %s: %s" % (e.code, detail)
  77. except Exception as e: # noqa: BLE001 — 网络/超时等失败都归档并带回原因
  78. return "archived", str(e)
  79. def _send_via_smtp(to: str, subject: str, body: str, html: str | None = None) -> tuple:
  80. from email.mime.multipart import MIMEMultipart
  81. host = os.environ["PL_SMTP_HOST"]
  82. port = int(os.environ.get("PL_SMTP_PORT", "465"))
  83. user = os.environ.get("PL_SMTP_USER", "")
  84. password = os.environ.get("PL_SMTP_PASSWORD", "")
  85. from_addr = os.environ.get("PL_SMTP_FROM") or _from_addr()
  86. use_ssl = os.environ.get("PL_SMTP_SSL", "1") == "1"
  87. try:
  88. if html:
  89. msg = MIMEMultipart("alternative")
  90. msg.attach(MIMEText(body, "plain", "utf-8"))
  91. msg.attach(MIMEText(html, "html", "utf-8"))
  92. else:
  93. msg = MIMEText(body, "plain", "utf-8")
  94. msg["Subject"] = Header(subject, "utf-8")
  95. msg["From"] = formataddr((str(Header(DEFAULT_FROM_NAME, "utf-8")), from_addr))
  96. msg["To"] = to
  97. if use_ssl:
  98. server = smtplib.SMTP_SSL(host, port, timeout=15)
  99. else:
  100. server = smtplib.SMTP(host, port, timeout=15)
  101. server.starttls()
  102. try:
  103. if user:
  104. server.login(user, password)
  105. server.sendmail(from_addr, [to], msg.as_string())
  106. finally:
  107. server.quit()
  108. return "sent", None
  109. except Exception as e: # noqa: BLE001 — SMTP 各类失败都归档并带回原因
  110. return "archived", str(e)