email_service.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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 = "袋研社 POUCHLAB"
  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) -> tuple:
  35. """返回 (status, error):status = sent | archived。"""
  36. if os.environ.get("PL_RESEND_API_KEY"):
  37. return _send_via_resend(to, subject, body)
  38. if os.environ.get("PL_SMTP_HOST"):
  39. return _send_via_smtp(to, subject, body)
  40. return "archived", None
  41. def _send_via_resend(to: str, subject: str, body: str) -> tuple:
  42. # 调用方传入的是纯文本,同时给出 text 与转义后的 html
  43. html_body = (
  44. '<div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;'
  45. 'line-height:1.7;color:#222">'
  46. + html_lib.escape(body).replace("\n", "<br>\n")
  47. + "</div>"
  48. )
  49. payload = {
  50. "from": _from_header(),
  51. "to": [to],
  52. "subject": subject,
  53. "text": body,
  54. "html": html_body,
  55. }
  56. req = urllib.request.Request(
  57. RESEND_API,
  58. data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
  59. headers={
  60. "Authorization": "Bearer " + os.environ["PL_RESEND_API_KEY"].strip(),
  61. "Content-Type": "application/json",
  62. # Resend 前置的 Cloudflare 会拦截默认 UA Python-urllib/x(403 1010)
  63. "User-Agent": "pouchlab-mailer/1.0",
  64. },
  65. method="POST",
  66. )
  67. try:
  68. with urllib.request.urlopen(req, timeout=15) as resp:
  69. if 200 <= resp.status < 300:
  70. return "sent", None
  71. return "archived", "Resend HTTP %s" % resp.status
  72. except urllib.error.HTTPError as e:
  73. detail = e.read().decode("utf-8", "replace")[:500]
  74. return "archived", "Resend %s: %s" % (e.code, detail)
  75. except Exception as e: # noqa: BLE001 — 网络/超时等失败都归档并带回原因
  76. return "archived", str(e)
  77. def _send_via_smtp(to: str, subject: str, body: str) -> tuple:
  78. host = os.environ["PL_SMTP_HOST"]
  79. port = int(os.environ.get("PL_SMTP_PORT", "465"))
  80. user = os.environ.get("PL_SMTP_USER", "")
  81. password = os.environ.get("PL_SMTP_PASSWORD", "")
  82. from_addr = os.environ.get("PL_SMTP_FROM") or _from_addr()
  83. use_ssl = os.environ.get("PL_SMTP_SSL", "1") == "1"
  84. try:
  85. msg = MIMEText(body, "plain", "utf-8")
  86. msg["Subject"] = Header(subject, "utf-8")
  87. msg["From"] = formataddr((str(Header(DEFAULT_FROM_NAME, "utf-8")), from_addr))
  88. msg["To"] = to
  89. if use_ssl:
  90. server = smtplib.SMTP_SSL(host, port, timeout=15)
  91. else:
  92. server = smtplib.SMTP(host, port, timeout=15)
  93. server.starttls()
  94. try:
  95. if user:
  96. server.login(user, password)
  97. server.sendmail(from_addr, [to], msg.as_string())
  98. finally:
  99. server.quit()
  100. return "sent", None
  101. except Exception as e: # noqa: BLE001 — SMTP 各类失败都归档并带回原因
  102. return "archived", str(e)