Files
project-panel/routes_email.py

67 lines
2.6 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
"""
邮件通知 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}")
if not data:
log_message(f"❌ 无效数据: content-type={request.content_type}")
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}")
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