58 lines
1.8 KiB
Python
58 lines
1.8 KiB
Python
|
|
#!/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', 'favor@tphai.com')
|
||
|
|
smtp_pass = os.environ.get('SMTP_PASS', 'favor@!')
|
||
|
|
|
||
|
|
# 创建邮件
|
||
|
|
msg = MIMEMultipart()
|
||
|
|
msg['From'] = smtp_user
|
||
|
|
msg['To'] = to_email
|
||
|
|
msg['Subject'] = subject
|
||
|
|
|
||
|
|
# 添加正文
|
||
|
|
msg.attach(MIMEText(body, 'plain', 'utf-8'))
|
||
|
|
|
||
|
|
# 发送邮件
|
||
|
|
server = smtplib.SMTP(smtp_host, smtp_port)
|
||
|
|
server.login(smtp_user, smtp_pass)
|
||
|
|
server.send_message(msg)
|
||
|
|
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
|