python3 发送邮件 send mail 使用 163 smtp服务器

监控本地网络速度,通过api 请求速度,发现速度异常,发送报警邮件:

#! /usr/bin/env python3  
# -*- coding: UTF-8 -*-  
import smtplib ,time
from email.mime.text import MIMEText  
import requests

mailto_list=['×××××@163.com',"×××××××@qq.com"]  #receiver mail address

mail_host="smtp.163.com"            #smtp server 
mail_user="*********@163.com"       #your 163 mail username  
mail_pass="×××××××××××"             #your 163 mail password,使用授权码登录不要用登录,具体见163邮箱中的设置  
mail_postfix="163.com"              #mail suffix,163.com  

def send_mail(to_list,title,sub,content):  
    me=title+"<"+mail_user+"@"+mail_postfix+">"  
    msg = MIMEText(content,_subtype='plain',_charset='utf-8')  
    msg['Subject'] = sub  
    msg['From'] = me  
    msg['To'] = ";".join(to_list)                #reciever use ';' split  
    try:  
        server = smtplib.SMTP()  
        server.connect(mail_host)                #connect to server  
        server.login(mail_user,mail_pass)        #login server
        server.sendmail(me, to_list, msg.as_string())  
        server.close()  
        return True  
    except Exception as e:  
        print(e)  
        return False  

def check_speed(api='http://192.168.50.172:5050/data/speed'):
    try:
        resp = requests.get(api)
        if resp.status_code == 200:
            speed = resp.json()['download_speed']
            print("speed:",speed)
            if speed > 15000:
                return ["speed lower than 15000, actual speed is "+str(speed)]
            else :
                return None
        return [str(resp.status_code)+" requests api fail!!!"]
    except Exception as e:
        return ["requests api fail!!!"]

if __name__ == '__main__':
    while True:
        ret = check_speed()
        print(ret)
        if ret:
            send_mail(mailto_list,"speed","speed monitor",ret[0])  
        print("sleep")
        time.sleep(180)     

猜你喜欢

转载自blog.csdn.net/zeli1511/article/details/79507740