Files
project-panel/routes_email.py
T

67 lines
2.6 KiB
Python
Raw Normal View History

2026-06-01 12:30:24 +08:00
#!/usr/bin/env python3
"""
邮件通知 API 路由
"""
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from flask import jsonify, request
from utils import log_message
def register_email_routes(app):
"""注册邮件通知相关路由"""
@app.route('/api/email/send', methods=['POST'])
def api_email_send():
"""发送邮件通知"""
data = request.get_json()
log_message(f"📨 收到邮件请求: {data}")
2026-06-01 12:30:24 +08:00
if not data:
log_message(f"❌ 无效数据: content-type={request.content_type}")
2026-06-01 12:30:24 +08:00
return jsonify({'error': '无效数据'}), 400
to_email = data.get('to')
subject = data.get('subject')
body = data.get('body')
if not to_email or not subject or not body:
log_message(f"❌ 缺少参数: to={to_email}, subject={subject}, body_len={len(body) if body else 0}")
2026-06-01 12:30:24 +08:00
return jsonify({'error': '缺少必要参数'}), 400
try:
# SMTP配置 (从环境变量或默认值)
smtp_host = os.environ.get('SMTP_HOST', 'mail.tphai.com')
smtp_port = int(os.environ.get('SMTP_PORT', 587))
2026-06-01 17:28:31 +08:00
smtp_user = os.environ.get('SMTP_USER', 'hz4th_coder@tphai.com')
smtp_pass = os.environ.get('SMTP_PASS', 'hz4th_coder@!')
2026-06-01 12:30:24 +08:00
log_message(f"📧 准备发送邮件: to={to_email}, subject={subject}, user={smtp_user}")
# 创建邮件(完全对齐 send_email.py 的方式)
from email.utils import formataddr, formatdate
2026-06-01 12:30:24 +08:00
msg = MIMEMultipart()
2026-06-01 17:28:31 +08:00
msg['From'] = formataddr(('黄庄4号程序员', smtp_user))
2026-06-01 12:30:24 +08:00
msg['To'] = to_email
msg['Subject'] = subject
msg['Date'] = formatdate(localtime=True)
2026-06-01 12:30:24 +08:00
# 添加正文
msg.attach(MIMEText(body, 'plain', 'utf-8'))
# 发送邮件(无SSL模式,完全对齐 send_email.py
2026-06-01 12:30:24 +08:00
server = smtplib.SMTP(smtp_host, smtp_port)
2026-06-01 17:28:31 +08:00
server.ehlo()
2026-06-01 12:30:24 +08:00
server.login(smtp_user, smtp_pass)
# 使用 sendmail 而非 send_message,与已验证成功的脚本一致
server.sendmail(smtp_user, [to_email], msg.as_string())
2026-06-01 12:30:24 +08:00
server.quit()
log_message(f"✅ 邮件发送成功: {subject} -> {to_email}")
2026-06-01 12:30:24 +08:00
return jsonify({'message': '邮件发送成功'})
except Exception as e:
log_message(f"❌ 邮件发送失败: {e}")
2026-06-01 12:30:24 +08:00
return jsonify({'error': str(e)}), 500