import os
import smtplib
from email.message import EmailMessage
from datetime import datetime as dt
def email_alert(subject,body,to):
msg = EmailMessage()
msg.set_content(body)
msg['subject'] = subject
msg['to'] = to
user = "
[email protected]"
msg['from'] = user
server = smtplib.SMTP("smtprelay.corp.chxx.com", 25)
server.starttls()
#server.login(user,password)
server.send_message(msg)
server.quit()
def check_file(file_name):
alert = None
try:
file_stat = os.stat(file_name)
except FileNotFoundError:
alert = f'File {file_name} does not exist'
except Exception as err:
alert = f'Can not get file stats for file {file_name} because of error {str(err)}'
else:
file_age=(dt.utcnow()-dt.utcfromtimestamp(os.stat(file_name).st_mtime)).total_seconds()
if file_age>24*60*60:
days = int(file_age/(24*60*60))
hours = int((file_age%(24*60*60))/3600)
mins = int((file_age%3600)/60)
secs = int(file_age%60)
alert = ('File {file:s} is {days:d} days and {hours:02d}:{mins:02d}:{secs:02d} hours old'
.format(file=file_name,days=days,hours=hours,mins=mins,secs=secs))
if alert is not None:
print(f'eMail alert: {alert}')
# email_alert('Service-Data-Now failure alert', alert, '
[email protected]')
else:
print(f'Everything is fine with file {file_name}. No email alert!')
if __name__ == '__main__':
path = 'C:/Python'
file = 'Data.csv'
check_file(os.path.join(path,file))
file='./test.file'
f = open(file,'w')
f.write('test data')
f.close()
check_file(file)
yesterday = (dt.utcnow()-dt.utcfromtimestamp(0)).total_seconds()-(24*60*60+2*60*60+13*60+35)
os.utime(file,(yesterday,yesterday))
check_file(file)
os.remove(file)