Files
xbcr/email_utils.py

140 lines
5.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""邮件发送模块。SMTP 凭据从 smtp_config.txt 读取(见 .gitignore,不入库不入 Git)。
smtp_config.txt 格式(键=值,# 开头为注释):
smtp_host=smtp.qq.com
smtp_port=587
smtp_user=xxx@qq.com
smtp_pass=授权码
"""
import html
import smtplib
from pathlib import Path
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
_SMTP_CONFIG_PATH = Path(__file__).parent / "smtp_config.txt"
def render_email_html(kicker, title, lead, details=None, button_url="",
button_text="打开处理", accent="#2563eb",
code=None, footnote=None):
"""通用 HTML 邮件模板(与租车/告警邮件同一套视觉)。
code 非空时渲染成醒目的大号验证码区块(用于注册/重置密码验证码)。
注意:调用方应保证各参数为纯文本,本函数内部统一 html.escape,
不要把未经转义的 HTML 传进来。
"""
details = list(details or [])
rows = "".join(
'<tr><td style="padding:8px 0;color:#64748b;width:110px;vertical-align:top">'
'{}</td><td style="padding:8px 0;color:#0f172a;font-weight:600">{}</td></tr>'.format(
html.escape(str(label)), html.escape(str(value)))
for label, value in details)
table = ""
if rows:
table = (
'<table role="presentation" style="width:100%;border-collapse:collapse;'
'background:#f8fafc;border-radius:12px;padding:12px">' + rows + '</table>')
code_block = ""
if code:
code_block = f"""
<div style="margin:6px 0 22px;padding:20px 12px;text-align:center;
background:#f1f5f9;border:1px dashed {accent};border-radius:14px">
<div style="font-size:12px;color:#64748b;letter-spacing:.12em;margin-bottom:10px">验证码</div>
<div style="font-size:34px;font-weight:800;letter-spacing:.28em;color:#0f172a;
font-family:Consolas,Monaco,'Courier New',monospace;
font-variant-numeric:tabular-nums">{html.escape(str(code))}</div>
</div>"""
button = ""
if button_url:
safe_url = html.escape(button_url, quote=True)
button = f"""
<div style="margin:28px 0 12px;text-align:center">
<a href="{safe_url}" style="display:inline-block;background:{accent};color:#fff;
text-decoration:none;padding:13px 34px;border-radius:10px;
font-weight:700;font-size:16px">{html.escape(button_text)}</a>
</div>"""
foot = footnote if footnote is not None else "这是系统自动发送的邮件。"
return f"""<!doctype html>
<html><body style="margin:0;background:#f1f5f9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Microsoft YaHei',sans-serif">
<div style="max-width:600px;margin:0 auto;padding:30px 14px">
<div style="background:#fff;border-radius:18px;overflow:hidden;box-shadow:0 8px 30px rgba(15,23,42,.08)">
<div style="height:6px;background:{accent}"></div>
<div style="padding:30px">
<div style="font-size:13px;color:{accent};font-weight:800;letter-spacing:.08em">{html.escape(kicker)}</div>
<h1 style="margin:10px 0 12px;font-size:24px;line-height:1.35;color:#0f172a">{html.escape(title)}</h1>
<p style="margin:0 0 22px;color:#475569;font-size:15px;line-height:1.8">{html.escape(lead)}</p>
{code_block}
{table}
{button}
</div>
</div>
<p style="text-align:center;color:#94a3b8;font-size:12px;margin:18px 0">{html.escape(str(foot))}</p>
</div>
</body></html>"""
def render_email_safe(**kwargs):
"""render_email_html 的失败兜底包装:任何异常都返回 None,
让调用方退回纯文本发送。验证码/告警属关键路径,不能因样式渲染失败而发不出去。"""
try:
return render_email_html(**kwargs)
except Exception as e:
print(f"[邮件渲染] HTML 渲染失败,退回纯文本: {e}")
return None
def _load_smtp_config() -> dict:
cfg = {"smtp_host": "smtp.qq.com", "smtp_port": "587", "smtp_starttls": "1",
"smtp_user": "", "smtp_pass": ""}
try:
if _SMTP_CONFIG_PATH.exists():
for line in _SMTP_CONFIG_PATH.read_text("utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, v = line.split("=", 1)
k = k.strip()
if k in cfg:
cfg[k] = v.strip()
except Exception as e:
print(f"[SMTP配置] 读取失败: {e}")
return cfg
def send_email(to_email: str, subject: str, body: str, html_body: str = None) -> bool:
"""发送邮件,可同时提供纯文本和 HTML 版本,返回是否成功。"""
cfg = _load_smtp_config()
if not cfg["smtp_user"] or not cfg["smtp_pass"]:
print("[邮件发送失败] smtp_config.txt 未配置 smtp_user/smtp_pass")
return False
try:
if html_body:
msg = MIMEMultipart("alternative")
msg.attach(MIMEText(body, "plain", "utf-8"))
msg.attach(MIMEText(html_body, "html", "utf-8"))
else:
msg = MIMEText(body, "plain", "utf-8")
msg["From"] = cfg["smtp_user"]
msg["To"] = to_email
msg["Subject"] = Header(subject, "utf-8")
server = smtplib.SMTP(cfg["smtp_host"], int(cfg["smtp_port"]), timeout=10)
if cfg["smtp_starttls"] == "1":
server.starttls()
server.login(cfg["smtp_user"], cfg["smtp_pass"])
server.sendmail(cfg["smtp_user"], [to_email], msg.as_string())
server.quit()
print(f"[邮件发送成功] 收件: {to_email} | 主题: {subject}")
return True
except Exception as e:
print(f"[邮件发送失败] 收件: {to_email} | 错误: {e}")
return False