1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| import json import smtplib import os from email.mime.text import MIMEText from email.header import Header from flask import Flask, request
app = Flask(__name__)
SMTP_HOST = os.getenv('SMTP_HOST', 'smtp.139.com') SMTP_PORT = int(os.getenv('SMTP_PORT', 25)) SMTP_USER = os.getenv('SMTP_USER', '15398009149@139.com') SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '36edaxxxxx25da00') FROM_ADDR = os.getenv('FROM_ADDR', '15398009149@139.com')
TO_ADDRS = os.getenv('TO_ADDRS', '15398009149@139.com').split(',')
FLASK_PORT = int(os.getenv('FLASK_PORT', 5000))
def format_content(template, data): """ 根据模板和数据格式化内容 :param template: 模板字符串(包含占位符) :param data: 替换占位符的数据(字典格式) :return: 格式化后的字符串 """ try: formatted_content = template for key, value in data.items(): if isinstance(value, dict): for sub_key, sub_value in value.items(): placeholder = "{{ ." + key + "." + sub_key + " }}" formatted_content = formatted_content.replace(placeholder, str(sub_value)) else: placeholder = "{{ ." + key + " }}" formatted_content = formatted_content.replace(placeholder, str(value)) return formatted_content except Exception as e: print(f"格式化内容失败: {e}") return template
def send_mail(content, to_addrs): """ 发送邮件 :param content: 邮件内容 :param to_addrs: 收件人邮箱地址列表 """ message = MIMEText(content, 'plain', 'utf-8') message['From'] = Header(FROM_ADDR, 'utf-8') message['To'] = Header(','.join(to_addrs), 'utf-8') message['Subject'] = Header('集群事件告警通知', 'utf-8')
try: with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as smtp_obj: smtp_obj.login(SMTP_USER, SMTP_PASSWORD) smtp_obj.sendmail(FROM_ADDR, to_addrs, message.as_string()) print(f"邮件发送成功,收件人: {', '.join(to_addrs)}") except Exception as err: print(f"邮件发送失败: {str(err)}")
@app.route("/send_mail", methods=["POST"]) def send(): """ 处理 Webhook 请求并发送邮件 """ raw_data = request.data.decode('utf-8') try: data = json.loads(raw_data) if "text" in data and "content" in data["text"]: content = data["text"]["content"] else: content = "集群事件告警" to_addrs = data.get("to_addrs", TO_ADDRS) formatted_content = content send_mail(formatted_content, to_addrs) return "邮件发送成功。" except Exception as e: print(f"处理请求失败: {e}") return "邮件发送失败。", 500
if __name__ == "__main__": app.run("0.0.0.0", FLASK_PORT)
|