Files
project-panel/routes_email.py
hz4th_coder 23810cf180 fix: 邮件发送改为 sendmail + Date头,对齐已验证脚本
- send_message() → sendmail()(与 send_email.py 一致)
- 新增 Date 头(部分SMTP服务器缺少会拦截)
- 增加发送前/后详细日志
2026-06-01 17:37:39 +08:00

64 lines
2.4 KiB
Python
Raw 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
"""
邮件通知 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()
if not data:
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:
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))
smtp_user = os.environ.get('SMTP_USER', 'hz4th_coder@tphai.com')
smtp_pass = os.environ.get('SMTP_PASS', 'hz4th_coder@!')
log_message(f"📧 准备发送邮件: to={to_email}, subject={subject}, user={smtp_user}")
# 创建邮件(完全对齐 send_email.py 的方式)
from email.utils import formataddr, formatdate
msg = MIMEMultipart()
msg['From'] = formataddr(('黄庄4号程序员', smtp_user))
msg['To'] = to_email
msg['Subject'] = subject
msg['Date'] = formatdate(localtime=True)
# 添加正文
msg.attach(MIMEText(body, 'plain', 'utf-8'))
# 发送邮件无SSL模式完全对齐 send_email.py
server = smtplib.SMTP(smtp_host, smtp_port)
server.ehlo()
server.login(smtp_user, smtp_pass)
# 使用 sendmail 而非 send_message与已验证成功的脚本一致
server.sendmail(smtp_user, [to_email], msg.as_string())
server.quit()
log_message(f"✅ 邮件发送成功: {subject} -> {to_email}")
return jsonify({'message': '邮件发送成功'})
except Exception as e:
log_message(f"❌ 邮件发送失败: {e}")
return jsonify({'error': str(e)}), 500