這篇文章主要講解了基于Python腳本實(shí)現(xiàn)郵件報(bào)警功能的方法,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站與策劃設(shè)計(jì),阿拉爾網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十載,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:阿拉爾等地區(qū)。阿拉爾做網(wǎng)站價(jià)格咨詢:18980820575使用了smtplib等第三方庫(kù),進(jìn)行發(fā)送郵件,完成郵件報(bào)警功能
如下是實(shí)例 :
#!/usr/bin/python import glob import operator from optparse import OptionParser import smtplib import email.MIMEText as MIMEText import email.Utils.formadate as formatdate msg = "" #主方法 def main(): global options global msg parser = OptionParser(add_help_option=False) parser.add_option("-m", "--mail", dest="mail", type="str", help="email address to send report result (comma separated)") parser.add_option("-t", "--title", dest="title", type="str", help="email title (default:Error File Count)") parser.add_option("-a", "--admin", dest="admin", type="str", help="set sender address. works with -m option") (options, args) = parser.parse_args() #這里監(jiān)控文件夾下的文件數(shù),超出25個(gè)文件即報(bào)警 datanum = cntFiles("/data/","csv") if (operator.gt(datanum,25)): msg += " Please be alert : \n the number of files under /data/ path is greater than 25 :" msg += "\n ==========================================" msg += "\n The number of files is : " + str(datanum) sendmsg(options,msg) print("==== end ====") #添加發(fā)送郵件的信息 def sendmsg(options,msg): if options.mail: toAddr = options.mail if options.admin: fromAddr = options.admin else: fromAddr = 'zhangsan@neiyou.cn'#這里是公司的公用SMTP郵箱賬號(hào) if options.title: subject = options.title else: subject = 'File Stacking Alarm' msg += "\n ========================================== \n" print( msg) msg = createMsg(fromAddr, toAddr, subject, msg) print( msg) send(fromAddr, toAddr, msg) else: print( msg) #glob方法,統(tǒng)計(jì)文件夾下的文件數(shù) def cntFiles(in_directory, ext): stage = len(glob.glob1(in_directory,"*." + ext)) return stage #創(chuàng)建郵件頭 def createMsg(fromAddr, toAddr, subject, body): msg = MIMEText(body) msg['Subject'] = subject msg['To'] = toAddr msg['From'] = fromAddr msg['Date'] = formatdate() return msg #發(fā)送郵件 def send(fromAddr, toAddr, msg): try: #這里添加公司的SMTP郵箱地址 s = smtplib.SMTP('192.168.12.120') s.sendmail(fromAddr, toAddr.split(','), msg.as_string()) s.close() print("SUCCESS: sending email") except smtplib.SMTPException: print("ERROR: sending email") if __name__ == '__main__': main()