#!/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(
'
| '
'{} | {} |
'.format(
html.escape(str(label)), html.escape(str(value)))
for label, value in details)
table = ""
if rows:
table = (
'')
code_block = ""
if code:
code_block = f"""
验证码
{html.escape(str(code))}
"""
button = ""
if button_url:
safe_url = html.escape(button_url, quote=True)
button = f"""
"""
foot = footnote if footnote is not None else "这是系统自动发送的邮件。"
return f"""
{html.escape(kicker)}
{html.escape(title)}
{html.escape(lead)}
{code_block}
{table}
{button}
{html.escape(str(foot))}
"""
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}")
import os
for key in cfg:
if os.environ.get(key.upper()) is not None:
cfg[key] = os.environ[key.upper()]
return cfg
def send_email(to_email: str, subject: str, body: str, html_body: str = None) -> bool:
from runtime_mode import PREVIEW_MODE
if PREVIEW_MODE and str(to_email).lower() in ("demo@preview.local", "friend@preview.local"):
return True # Demonstration recipients are synthetic; real alert emails use SMTP.
"""发送邮件,可同时提供纯文本和 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