astock-agent/backend/app/core/email.py
2026-04-24 09:00:46 +08:00

51 lines
2.1 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.

"""SMTP 邮件发送工具。"""
from __future__ import annotations
import smtplib
from email.message import EmailMessage
from app.config import settings
def send_email(subject: str, to_email: str, html: str, text: str | None = None) -> None:
if not settings.smtp_host or not settings.smtp_sender or not settings.smtp_username or not settings.smtp_password:
raise RuntimeError("SMTP 配置不完整")
message = EmailMessage()
message["Subject"] = subject
message["From"] = settings.smtp_sender
message["To"] = to_email
message.set_content(text or subject)
message.add_alternative(html, subtype="html")
if settings.smtp_use_ssl:
with smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port) as server:
server.login(settings.smtp_username, settings.smtp_password)
server.send_message(message)
else:
with smtplib.SMTP(settings.smtp_host, settings.smtp_port) as server:
server.starttls()
server.login(settings.smtp_username, settings.smtp_password)
server.send_message(message)
def build_register_code_email(code: str) -> tuple[str, str]:
subject = "AStock Agent 注册验证码"
html = f"""
<html>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; color: #111827;">
<div style="max-width: 520px; margin: 0 auto; padding: 24px;">
<h2 style="margin: 0 0 12px;">注册验证码</h2>
<p style="margin: 0 0 16px; color: #4b5563;">你正在注册 AStock Agent请使用以下验证码完成注册</p>
<div style="font-size: 28px; font-weight: 700; letter-spacing: 6px; padding: 14px 18px; background: #fff7ed; color: #b45309; border-radius: 12px; display: inline-block;">
{code}
</div>
<p style="margin: 16px 0 0; color: #6b7280;">验证码 {settings.email_code_expiry_minutes} 分钟内有效,请勿泄露给他人。</p>
</div>
</body>
</html>
"""
text = f"你正在注册 AStock Agent验证码为{code}{settings.email_code_expiry_minutes} 分钟内有效。"
return subject, html, text