python实现微信及邮件报警

时间:2025-01-31 07:23:40

要想使用微信报警,首先需要在微信平台注册微信企业号并创建应用ID:/?from=qyh_redirect

以下是测试demo,如有错误还请指正,运行错误还望自行解决,谢谢!

#coding=utf-8

import json
import time
import urllib2

options = {
    'WeiXin': {
            'corp_id': 'wwf8***',  #微信企业号ID
            'agent_id': '1000002', #微信企业号应用ID
            'agent_secret': 'wGu_wHU5pe***',  #微信企业号密钥
            'to_user': '@all'  #发送给谁
    },
}
class WeiXinSendMsg:
    def __init__(self, wx_conf):
        self.corp_id = wx_conf.get('corp_id')
        self.agent_secret = wx_conf.get('agent_secret')
        self.agent_id = wx_conf.get('agent_id')
        self.to_user = wx_conf.get('to_user')
         = self.get_token() 
        self.token_update_time = int(())
        
    def get_token(self):
        get_token_url = '/cgi-bin/gettoken?corpid=' + self.corp_id + '&corpsecret=' + self.agent_secret
        token = ((get_token_url).read().decode('utf-8'))['access_token']
        if token:
            return token

    # 微信发送端的token每1800秒会更新一次
    def update_token(self):
        if int(()) - self.token_update_time >= 1800:
             = self.get_token()
            self.token_update_time = int(())

    def send_message(self, msg):
        try:
            self.update_token()
            send_url = '/cgi-bin/message/send?access_token=' + 
            send_val = {"touser":self.to_user, "toparty":"", "msgtype":"text", "agentid":self.agent_id, "text":{"content":msg}, "safe":"0"}
            send_data = (send_val, ensure_ascii=True, encoding='utf-8')
            send_request = (send_url, send_data)
            response = ((send_request).read())
        except Exception as e:
            print 'Exception WeiXin send_message:', e
if __name__ == '__main__':
	WeiXin = WeiXinSendMsg(('WeiXin'))
    WeiXin.send_message('hello world!')

#coding=utf-8

import smtplib
from  import Header
from  import MIMEText
from  import parseaddr, formataddr

options = {
    'Email': {
        'smtp_server': '',  #邮箱服务器地址
        'from_addr': 'monitor@',  #发送人账号
        'password': '123456', #发送人密码
        'to_addr': ['hanbo@', 'hanbo@'], #发送给谁
    }
}

class EmailSendMsg:
    def __init__(self, email_conf):
        self.smtp_server = email_conf.get('smtp_server')
        self.from_addr = email_conf.get('from_addr')
         = email_conf.get('password')
        self.to_addr = email_conf.get('to_addr')

    # def __del__(self):
    #     ()

    def format_addr(self, str):
        name, addr = parseaddr(str)
        return formataddr(( \
            Header(name, 'utf-8').encode(), \
            ('utf-8') if isinstance(addr, unicode) else addr))
    
    def send_msg(self, text):
        try:
             = (self.smtp_server, 25)
            .set_debuglevel(1)
            (self.from_addr, )

            msg = MIMEText(text, 'plain', 'utf-8')
            msg['From'] = self.format_addr(u'监控 <%s>' % self.from_addr)
            for i in range(len(self.to_addr)):
                msg['To'] = self.format_addr(u'<%s>' % self.to_addr[i])
            msg['Subject'] = Header(u'异常报警…', 'utf-8').encode()
            (self.from_addr, self.to_addr, msg.as_string())

            ()
        except Exception as e:
            print 'Exception Email send_message:', e

if __name__ == '__main__':
	Email = EmailSendMsg(('Email'))
	Email.send_msg('hello world!')