Reputation: 293
So, I have created this simple program, which checks my research data every hour for nans. It works fine, but i want to improve the email that it sends me, when it finds a nan. At the moment, I can only get it to email me anything that i put inside three speech marks, like this
message = """Missing data, yo."""
I want it to email me the datetime and file name when it has a nan. I have tried the following, but it doesnt work:
message = f"Hello, Cairan. {full_name} has missing data."
and I have tried this, which doesnt work:
message = """Missing data """ + full_name
I dont know what i am doing wrong here - please help. I would also be grateful for any advice on how to change the subject title for the email.
Thanks!
# -*- coding: utf-8 -*-
"""
This Python script was written for use on an Amazon EC2 server, with the Eltek GPRS Server running.
This code has a 60 minute loop, which:
1. Copies the data from its original location to a temporary 'checking' directory.
2. Imports the listed CSV files
3. Converts all 'No Data' into nans
4. Looks at the last 12 observations and checks if there is any nans - if there are any it will email an email address about the nans.
5. Loops over all files
6. Loops every hour
"""
# Import packages
import os #os
import fnmatch #fn match
import pandas as pd #pandas
import numpy as np #numpy
import sched #scheduler
import time # time
import smtplib #for email
import ssl #for email
from datetime import datetime #datetime
from termcolor import colored #for colouring text
from shutil import copyfile
# Scheduler
s = sched.scheduler(time.time, time.sleep)
# Email
user = '####@gmail.com' #email username (gmail tested and working)
sender = '####@gmail.com' #sendee email address
password = '####' #email password
port = 465 #port - 465 standard
recieve = '####'
context = ssl.create_default_context()
directory = "C:/EltekGateway/"
individual_files = "K01817-12158.csv", "K01830-12197.csv", "K01830-12200.csv"
files = "C:/EltekGateway/checking/K01817-12158.csv", "C:/EltekGateway/checking/K01830-12197.csv", "C:/EltekGateway/checking/K01830-12200.csv"
for full_name in individual_files:
checking_dir = directory + "checking/" + full_name
original_dir = directory + full_name
copyfile(original_dir, checking_dir)
print(original_dir, checking_dir)
def do_something(sc):
now = datetime.now()
print('<---------------------------------------------------------------------------------->')
print('Checking:' , len(files), 'datafiles.', 'Time now =', now)
for full_name in files:
df_tmp= pd.read_csv(full_name, skiprows = 5) # read csv to df_tmp
df_tmp.rename({'TX Channel': 'date'}, axis=1, inplace=True) # rename cols
df_tmp['date'] = pd.to_datetime(df_tmp['date'], errors='raise', dayfirst=True) # create datetime col
df_tmp = df_tmp.replace('No Data', np.nan) # Eltek 'No Data' to nan
df_check = df_tmp[-12:]
df_check = df_check.isnull().values.any()
# df_check = df_check.isna() # Check last observation to see if there is a nan
df_check_time = df_tmp.date.iloc[-1] # Store datetime for last obs
now = datetime.now()
date_string = df_check_time.strftime("%Y/%m/%d, %H:%M:%S")
# print(df_check) #checking loop
if df_check.any() == 0: # Check
print(date_string, full_name + colored(' - There is NO missing data','green'))
# print()
else:
print(date_string, full_name + colored(' - There IS missing data', 'red'))
message = """Missing data, yo."""
# message = f"Hello, Cairan. {full_name} has missing data."
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(sender, password)
server.sendmail(sender, recieve, message)
# print(df_tmp) #checking loop
# print(full_name) #checking loop
# print(df_check_time) #checking loop
print('<---------------------------------------------------------------------------------->')
s.enter(3600, 1, do_something, (sc,))
def main():
s.enter(3600, 1, do_something, (s,))
s.run()
if __name__ == "__main__":
main()
Upvotes: 0
Views: 695
Reputation: 6780
Your message is malformed.
You have to write it with proper header and such, like so:
message = """\
From: Robot <[email protected]>
To: Persoon <[email protected]>
Subject: Something Fancy Happened!
Hi Persoon,
Your Thing caused Something Fancy!
Yours,
Robot.
"""
If you don't want to build the message manually, take a look at https://docs.python.org/3/library/email.html
Upvotes: 1