基於Python指令碼實現郵件報警功能

2021-10-06 23:44:56 字數 2769 閱讀 3166

使用了smtplib等第三方庫,進行傳送郵件,完成郵件報警功能

如下是例項 :

在學習過程中有什麼不懂得可以加我的

python學習qun,855408893

與你分享python企業當下人才需求及怎麼從零基礎學習好python,和學習什麼內容

#!/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 = '[email protected]'#這裡是公司的公用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()

linux上做計畫任務,把指令新增進計畫任務中:

errymsfileemail.py -m [email protected] -t "[error/$host] file stacking alarm"

Python 指令碼傳送郵件

使用python完成郵件自動傳送 usr bin python coding utf 8 import smtplib from email.header import header from email.mime.text import mimetext class email sender ob...

python郵件傳送指令碼

複製 usr bin python coding utf 8 author dengyike date 2010 09 28 version 1.0 description auto sending email with attachment file import email import mim...

使用python指令碼傳送郵件

import smtplib from email.mime.text import mimetext from email.header import header 傳送方 sender 163.com 接收方 receiver 163.com 中文需要utf 8引數,不好使需要調整 在這裡輸入郵...