资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

基于Python脚本实现邮件报警功能的方法-创新互联

这篇文章主要讲解了基于Python脚本实现邮件报警功能的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

创新互联是一家专注于成都网站设计、成都做网站与策划设计,阿拉尔网站建设哪家好?创新互联做网站,专注于网站建设十载,网设计领域的专业建站公司;建站业务涵盖:阿拉尔等地区。阿拉尔做网站价格咨询:18980820575

使用了smtplib等第三方库,进行发送邮件,完成邮件报警功能

如下是实例 :

#!/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()
 
  #这里监控文件夹下的文件数,超出25个文件即报警
  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 ====")
 
#添加发送邮件的信息
def sendmsg(options,msg):
  if options.mail:
    toAddr = options.mail
    if options.admin:
      fromAddr = options.admin
    else:
      fromAddr = 'zhangsan@neiyou.cn'#这里是公司的公用SMTP邮箱账号
 
    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方法,统计文件夹下的文件数
def cntFiles(in_directory, ext):
  stage = len(glob.glob1(in_directory,"*." + ext))
  return stage
 
#创建邮件头
def createMsg(fromAddr, toAddr, subject, body):
  msg = MIMEText(body)
  msg['Subject'] = subject
  msg['To'] = toAddr
  msg['From'] = fromAddr
  msg['Date'] = formatdate()
  return msg
 
#发送邮件
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()

文章名称:基于Python脚本实现邮件报警功能的方法-创新互联
当前网址:http://www.cdkjz.cn/article/jpjdi.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220