python实现微信及邮件报警

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

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

#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.token = self.get_token() 
        self.token_update_time = int(time.time())
        
    def get_token(self):
        get_token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + self.corp_id + '&corpsecret=' + self.agent_secret
        token = json.loads(urllib2.urlopen(get_token_url).read().decode('utf-8'))['access_token']
        if token:
            return token

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

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

EmailSendMsg.py

#coding=utf-8

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

options = {
    'Email': {
        'smtp_server': 'smtp.exmail.qq.com',  #邮箱服务器地址
        'from_addr': '[email protected]',  #发送人账号
        'password': '123456', #发送人密码
        'to_addr': ['[email protected]', '[email protected]'], #发送给谁
    }
}

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

    # def __del__(self):
    #     self.server.quit()

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

            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.server.sendmail(self.from_addr, self.to_addr, msg.as_string())

            self.server.quit()
        except Exception as e:
            print 'Exception Email send_message:', e

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

你可能感兴趣的:(Python篇)