You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用GET API获取JSON后存在离线设备时如何自动发送告警邮件

解决方案

步骤1:新增邮件发送工具函数

使用Python自带的smtplib和email模块实现邮件发送能力,无需安装第三方依赖,函数示例如下:

import smtplib
from email.mime.text import MIMEText
from email.header import Header
import os

def send_offline_alert(offline_df):
    # 基础配置,按需修改为实际值
    sender = 'alert@your-domain.com'
    receiver_list = ['ops@your-domain.com', 'it-manager@your-domain.com']
    smtp_server = 'smtp.your-domain.com'
    smtp_port = 465
    # 授权码建议从环境变量读取,不要硬编码到代码中
    auth_code = os.getenv('EMAIL_ALERT_AUTH_CODE')

    # 构造邮件内容
    device_count = len(offline_df)
    subject = f"【网络告警】当前存在{device_count}台离线设备"
    # 纯文本格式正文,如需更美观的展示可替换为HTML格式
    content = f"""
本次巡检发现以下离线设备:
{offline_devices.to_string(index=False)}

请基础设施团队及时排查处理。
    """
    # 若使用HTML格式,替换为以下两行
    # content = f"<h3>本次巡检发现以下离线设备:</h3>{offline_devices.to_html(index=False)}"
    # message = MIMEText(content, 'html', 'utf-8')

    message = MIMEText(content, 'plain', 'utf-8')
    message['From'] = Header(f"网络监控系统 <{sender}>", 'utf-8')
    message['To'] = Header(','.join(receiver_list), 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')

    # 执行发送逻辑
    try:
        smtp = smtplib.SMTP_SSL(smtp_server, smtp_port)
        smtp.login(sender, auth_code)
        smtp.sendmail(sender, receiver_list, message.as_string())
        smtp.quit()
        print("告警邮件发送成功")
    except Exception as e:
        print(f"告警邮件发送失败,错误:{str(e)}")

步骤2:修改现有主程序集成告警逻辑

无需修改status.py原有代码,只需在主程序获取到df变量后新增离线设备筛选和告警触发逻辑即可,修改后的主程序代码如下:

# 开头导入前面编写的send_offline_alert函数
while option != 0:
    if option == 1:
        print ("OranizationID has been selected")
        exec(open('orgId.py').read())
    elif option == 2:
        print ("Getting network status of all sites...")
        exec(open('status.py').read())
        df.to_excel("output.xlsx")
        # 新增告警逻辑
        offline_devices = df[df['status'] == 'offline']
        if len(offline_devices) > 0:
            print(f"发现{len(offline_devices)}台离线设备,触发告警流程")
            send_offline_alert(offline_devices)
        else:
            print("所有设备均在线,无需发送告警")

注意事项

  • 所有敏感信息(API密钥、邮箱授权码)禁止硬编码在代码中,建议通过环境变量、加密配置文件的方式读取,避免泄露
  • 如果离线设备数量较多,可将离线设备列表单独导出为Excel文件作为邮件附件发送,避免正文过长
  • 正式上线前建议先将收件人改为测试邮箱,验证告警触发规则、邮件内容显示均正常后再替换为正式收件人列表

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 20:39:03