Directly on the code:
# python3 # -*- coding: utf-8 -*- # 2017/06/16 by luohan from email.mime.text import MIMEText from email.header import Header from email.utils import parseaddr, formataddr import smtplib import time import os def get_size(start_path = '.'): total_size = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size / (1024 * 1024 * 1024) def _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) def send_mail(): from_addr = '**@**.com' passwd = '***' to_addrs = ['[email protected]', ' [email protected] ' ] MSG = MimeText ( ' the statistical server / dev / shm memory alarm ' , ' Plain ' , ' UTF-. 8 ' ) MSG [ ' the From ' ] = from_addr MSG [ ' the To ' ] = ' , ' .join (to_addrs) MSG [ ' the Subject ' ] = Header ( ' online server alarm ' , ' UTF-. 8 ' ) .encode () the try : smtp_server = 'smtp.exmail.qq.com' server = smtplib.SMTP_SSL(smtp_server, 465) server.login(from_addr, passwd) server.sendmail(from_addr, to_addrs, msg.as_string()) with open('/home/jobs/mail.log', 'a') as f: print('{}: send success'.format(time.time()), file=f) except smtplib.SMTPException as e: with open('/home/jobs/mailerr.log', 'a') as f: print('{}: send failed, {}'.format(time.time(), e), file=f) finally: server.quit() def check_dir_size(target_dir): dirsize = get_size(target_dir) # 超过12G,总大小16G if dirsize > 12: send_mail() check_dir_size('/dev/shm')
References:
Reproduced in: https: //www.cnblogs.com/gattaca/p/6690781.html