Notification rework - SMTP v0.3 - working ✅
This commit is contained in:
@@ -10,6 +10,7 @@ from email.mime.multipart import MIMEMultipart
|
|||||||
from email.mime.text import MIMEText
|
from email.mime.text import MIMEText
|
||||||
import smtplib
|
import smtplib
|
||||||
import socket
|
import socket
|
||||||
|
import ssl
|
||||||
|
|
||||||
# Replace these paths with the actual paths to your Pi.Alert directories
|
# Replace these paths with the actual paths to your Pi.Alert directories
|
||||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||||
@@ -72,7 +73,12 @@ def main():
|
|||||||
|
|
||||||
#-------------------------------------------------------------------------------
|
#-------------------------------------------------------------------------------
|
||||||
def check_config ():
|
def check_config ():
|
||||||
if get_setting_value('SMTP_SERVER') == '' or get_setting_value('SMTP_REPORT_FROM') == '' or get_setting_value('SMTP_REPORT_TO') == '':
|
|
||||||
|
server = get_setting_value('SMTP_SERVER')
|
||||||
|
report_to = get_setting_value("SMTP_REPORT_TO")
|
||||||
|
report_from = get_setting_value("SMTP_REPORT_FROM")
|
||||||
|
|
||||||
|
if server == '' or report_from == '' or report_to == '':
|
||||||
mylog('none', ['[Email Check Config] Error: Email service not set up correctly. Check your pialert.conf SMTP_*, SMTP_REPORT_FROM and SMTP_REPORT_TO variables.'])
|
mylog('none', ['[Email Check Config] Error: Email service not set up correctly. Check your pialert.conf SMTP_*, SMTP_REPORT_FROM and SMTP_REPORT_TO variables.'])
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
@@ -86,75 +92,81 @@ def send(pHTML, pText):
|
|||||||
# Compose email
|
# Compose email
|
||||||
msg = MIMEMultipart('alternative')
|
msg = MIMEMultipart('alternative')
|
||||||
msg['Subject'] = 'Pi.Alert Report'
|
msg['Subject'] = 'Pi.Alert Report'
|
||||||
msg['From'] = get_setting_value('SMTP_REPORT_FROM')
|
msg['From'] = get_setting_value("SMTP_REPORT_FROM")
|
||||||
msg['To'] = get_setting_value('SMTP_REPORT_TO')
|
msg['To'] = get_setting_value("SMTP_REPORT_TO")
|
||||||
msg.attach (MIMEText (pText, 'plain'))
|
msg.attach (MIMEText (pText, 'plain'))
|
||||||
msg.attach (MIMEText (pHTML, 'html'))
|
msg.attach (MIMEText (pHTML, 'html'))
|
||||||
|
|
||||||
failedAt = ''
|
# Set a timeout for the SMTP connection (in seconds)
|
||||||
|
smtp_timeout = 30
|
||||||
|
|
||||||
failedAt = print_log ('SMTP try')
|
mylog('debug', ['Trying to open connection to ' + str(get_setting_value('SMTP_SERVER')) + ':' + str(get_setting_value('SMTP_PORT'))])
|
||||||
|
|
||||||
try:
|
if get_setting_value("LOG_LEVEL") == 'debug':
|
||||||
# Send mail
|
|
||||||
failedAt = print_log('Trying to open connection to ' + str(get_setting_value('SMTP_SERVER')) + ':' + str(get_setting_value('SMTP_PORT')))
|
|
||||||
|
|
||||||
# Set a timeout for the SMTP connection (in seconds)
|
send_email(msg)
|
||||||
smtp_timeout = 30
|
|
||||||
|
|
||||||
if get_setting_value('SMTP_FORCE_SSL'):
|
else:
|
||||||
failedAt = print_log('SMTP_FORCE_SSL == True so using .SMTP_SSL()')
|
|
||||||
if get_setting_value('SMTP_PORT') == 0:
|
|
||||||
failedAt = print_log('SMTP_PORT == 0 so sending .SMTP_SSL(SMTP_SERVER)')
|
|
||||||
smtp_connection = smtplib.SMTP_SSL(get_setting_value('SMTP_SERVER'))
|
|
||||||
else:
|
|
||||||
failedAt = print_log('SMTP_PORT == 0 so sending .SMTP_SSL(SMTP_SERVER, SMTP_PORT)')
|
|
||||||
smtp_connection = smtplib.SMTP_SSL(get_setting_value('SMTP_SERVER'), get_setting_value('SMTP_PORT'), timeout=smtp_timeout)
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
send_email(msg)
|
||||||
|
|
||||||
|
except smtplib.SMTPAuthenticationError as e:
|
||||||
|
mylog('none', [' ERROR: Couldn\'t connect to the SMTP server (SMTPAuthenticationError)'])
|
||||||
|
mylog('none', [' ERROR: Double-check your SMTP_USER and SMTP_PASS settings.)'])
|
||||||
|
mylog('none', [' ERROR: ', str(e)])
|
||||||
|
except smtplib.SMTPServerDisconnected as e:
|
||||||
|
mylog('none', [' ERROR: Couldn\'t connect to the SMTP server (SMTPServerDisconnected)'])
|
||||||
|
mylog('none', [' ERROR: ', str(e)])
|
||||||
|
except socket.gaierror as e:
|
||||||
|
mylog('none', [' ERROR: Could not resolve hostname (socket.gaierror)'])
|
||||||
|
mylog('none', [' ERROR: ', str(e)])
|
||||||
|
except ssl.SSLError as e:
|
||||||
|
mylog('none', [' ERROR: Could not establish SSL connection (ssl.SSLError)'])
|
||||||
|
mylog('none', [' ERROR: Are you sure you need SMTP_FORCE_SSL enabled? Check your SMTP provider docs.'])
|
||||||
|
mylog('none', [' ERROR: ', str(e)])
|
||||||
|
|
||||||
|
def send_email(msg):
|
||||||
|
# Send mail
|
||||||
|
if get_setting_value('SMTP_FORCE_SSL'):
|
||||||
|
mylog('debug', ['SMTP_FORCE_SSL == True so using .SMTP_SSL()'])
|
||||||
|
if get_setting_value("SMTP_PORT") == 0:
|
||||||
|
mylog('debug', ['SMTP_PORT == 0 so sending .SMTP_SSL(SMTP_SERVER)'])
|
||||||
|
smtp_connection = smtplib.SMTP_SSL(get_setting_value('SMTP_SERVER'))
|
||||||
else:
|
else:
|
||||||
failedAt = print_log('SMTP_FORCE_SSL == False so using .SMTP()')
|
mylog('debug', ['SMTP_PORT == 0 so sending .SMTP_SSL(SMTP_SERVER, SMTP_PORT)'])
|
||||||
if get_setting_value('SMTP_PORT') == 0:
|
smtp_connection = smtplib.SMTP_SSL(get_setting_value('SMTP_SERVER'), get_setting_value('SMTP_PORT'), timeout=smtp_timeout)
|
||||||
failedAt = print_log('SMTP_PORT == 0 so sending .SMTP(SMTP_SERVER)')
|
|
||||||
smtp_connection = smtplib.SMTP (get_setting_value('SMTP_SERVER'))
|
|
||||||
else:
|
|
||||||
failedAt = print_log('SMTP_PORT == 0 so sending .SMTP(SMTP_SERVER, SMTP_PORT)')
|
|
||||||
smtp_connection = smtplib.SMTP (get_setting_value('SMTP_SERVER'), get_setting_value('SMTP_PORT'))
|
|
||||||
|
|
||||||
failedAt = print_log('Setting SMTP debug level')
|
else:
|
||||||
|
mylog('debug', ['SMTP_FORCE_SSL == False so using .SMTP()'])
|
||||||
|
if get_setting_value("SMTP_PORT") == 0:
|
||||||
|
mylog('debug', ['SMTP_PORT == 0 so sending .SMTP(SMTP_SERVER)'])
|
||||||
|
smtp_connection = smtplib.SMTP (get_setting_value('SMTP_SERVER'))
|
||||||
|
else:
|
||||||
|
mylog('debug', ['SMTP_PORT == 0 so sending .SMTP(SMTP_SERVER, SMTP_PORT)'])
|
||||||
|
smtp_connection = smtplib.SMTP (get_setting_value('SMTP_SERVER'), get_setting_value('SMTP_PORT'))
|
||||||
|
|
||||||
# Log level set to debug of the communication between SMTP server and client
|
mylog('debug', ['Setting SMTP debug level'])
|
||||||
if get_setting_value('LOG_LEVEL') == 'debug':
|
|
||||||
smtp_connection.set_debuglevel(1)
|
|
||||||
|
|
||||||
failedAt = print_log( 'Sending .ehlo()')
|
# Log level set to debug of the communication between SMTP server and client
|
||||||
|
if get_setting_value('LOG_LEVEL') == 'debug':
|
||||||
|
smtp_connection.set_debuglevel(1)
|
||||||
|
|
||||||
|
mylog('debug', [ 'Sending .ehlo()'])
|
||||||
|
smtp_connection.ehlo()
|
||||||
|
|
||||||
|
if not get_setting_value('SMTP_SKIP_TLS'):
|
||||||
|
mylog('debug', ['SMTP_SKIP_TLS == False so sending .starttls()'])
|
||||||
|
smtp_connection.starttls()
|
||||||
|
mylog('debug', ['SMTP_SKIP_TLS == False so sending .ehlo()'])
|
||||||
smtp_connection.ehlo()
|
smtp_connection.ehlo()
|
||||||
|
if not get_setting_value('SMTP_SKIP_LOGIN'):
|
||||||
|
mylog('debug', ['SMTP_SKIP_LOGIN == False so sending .login()'])
|
||||||
|
smtp_connection.login (get_setting_value('SMTP_USER'), get_setting_value('SMTP_PASS'))
|
||||||
|
|
||||||
if not get_setting_value('SMTP_SKIP_TLS'):
|
mylog('debug', ['Sending .sendmail()'])
|
||||||
failedAt = print_log('SMTP_SKIP_TLS == False so sending .starttls()')
|
smtp_connection.sendmail (get_setting_value("SMTP_REPORT_FROM"), get_setting_value("SMTP_REPORT_TO"), msg.as_string())
|
||||||
smtp_connection.starttls()
|
smtp_connection.quit()
|
||||||
failedAt = print_log('SMTP_SKIP_TLS == False so sending .ehlo()')
|
|
||||||
smtp_connection.ehlo()
|
|
||||||
if not get_setting_value('SMTP_SKIP_LOGIN'):
|
|
||||||
failedAt = print_log('SMTP_SKIP_LOGIN == False so sending .login()')
|
|
||||||
smtp_connection.login (get_setting_value('SMTP_USER'), get_setting_value('SMTP_PASS'))
|
|
||||||
|
|
||||||
failedAt = print_log('Sending .sendmail()')
|
|
||||||
smtp_connection.sendmail (get_setting_value('SMTP_REPORT_FROM'), get_setting_value('SMTP_REPORT_TO'), msg.as_string())
|
|
||||||
smtp_connection.quit()
|
|
||||||
except smtplib.SMTPAuthenticationError as e:
|
|
||||||
mylog('none', [' ERROR: Failed at - ', failedAt])
|
|
||||||
mylog('none', [' ERROR: Couldn\'t connect to the SMTP server (SMTPAuthenticationError), skipping Email (enable LOG_LEVEL=debug for more logging)'])
|
|
||||||
mylog('none', [' ERROR: ', str(e)])
|
|
||||||
except smtplib.SMTPServerDisconnected as e:
|
|
||||||
mylog('none', [' ERROR: Failed at - ', failedAt])
|
|
||||||
mylog('none', [' ERROR: Couldn\'t connect to the SMTP server (SMTPServerDisconnected), skipping Email (enable LOG_LEVEL=debug for more logging)'])
|
|
||||||
mylog('none', [' ERROR: ', str(e)])
|
|
||||||
except socket.gaierror as e:
|
|
||||||
mylog('none', [' ERROR: Failed at - ', failedAt])
|
|
||||||
mylog('none', [' ERROR: Could not resolve hostname (socket.gaierror), skipping Email (enable LOG_LEVEL=debug for more logging)'])
|
|
||||||
mylog('none', [' ERROR: ', str(e)])
|
|
||||||
|
|
||||||
mylog('debug', [f'[{pluginName}] Last executed - {str(failedAt)}'])
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
sys.exit(main())
|
sys.exit(main())
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ def create_new_devices (db):
|
|||||||
FROM CurrentScan"""
|
FROM CurrentScan"""
|
||||||
|
|
||||||
|
|
||||||
mylog('debug',f'[New Devices] 2 Create devices SQL: {sqlQuery}')
|
# mylog('debug',f'[New Devices] Create devices SQL: {sqlQuery}')
|
||||||
|
|
||||||
sql.execute (sqlQuery, (startTime, startTime) )
|
sql.execute (sqlQuery, (startTime, startTime) )
|
||||||
|
|
||||||
|
|||||||
@@ -273,26 +273,43 @@ def get_setting_value(key):
|
|||||||
|
|
||||||
setting = get_setting(key)
|
setting = get_setting(key)
|
||||||
|
|
||||||
|
value = ''
|
||||||
|
|
||||||
if setting is not None:
|
if setting is not None:
|
||||||
|
|
||||||
|
mylog('none', [f'[SETTINGS] setting json:{json.dumps(setting)}'])
|
||||||
|
|
||||||
|
|
||||||
|
set_type = 'Error: Not handled'
|
||||||
|
set_value = 'Error: Not handled'
|
||||||
|
|
||||||
set_value = setting["Value"] # Setting value
|
set_value = setting["Value"] # Setting value
|
||||||
set_type = setting["Type"] # Setting type
|
set_type = setting["Type"] # Setting type
|
||||||
|
|
||||||
# Handle different types of settings
|
# Handle different types of settings
|
||||||
if set_type in ['text', 'string', 'password', 'readonly', 'text.select']:
|
if set_type in ['text', 'string', 'password', 'readonly', 'text.select']:
|
||||||
return str(set_value)
|
value = str(set_value)
|
||||||
elif set_type in ['boolean', 'integer.checkbox']:
|
elif set_type in ['boolean', 'integer.checkbox']:
|
||||||
return bool(set_value)
|
|
||||||
|
value = True
|
||||||
|
|
||||||
|
if set_value in ['false', 'False', 'FALSE', 0]:
|
||||||
|
value = False
|
||||||
|
|
||||||
elif set_type in ['integer.select', 'integer']:
|
elif set_type in ['integer.select', 'integer']:
|
||||||
return int(set_value)
|
value = int(set_value)
|
||||||
elif set_type in ['text.multiselect', 'list', 'subnets']:
|
elif set_type in ['text.multiselect', 'list', 'subnets']:
|
||||||
# Assuming set_value is a list in this case
|
# Assuming set_value is a list in this case
|
||||||
return set_value
|
value = set_value
|
||||||
elif set_type == '.template':
|
elif set_type == '.template':
|
||||||
# Assuming set_value is a JSON object in this case
|
# Assuming set_value is a JSON object in this case
|
||||||
return json.loads(set_value)
|
value = json.loads(set_value)
|
||||||
|
else:
|
||||||
|
mylog('none', [f'[SETTINGS] ERROR - set_type not handled:{set_type}'])
|
||||||
|
mylog('none', [f'[SETTINGS] ERROR - setting json:{json.dumps(setting)}'])
|
||||||
|
|
||||||
return ''
|
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -485,6 +485,8 @@ def process_plugin_events(db, plugin, pluginsState, plugEventsArr):
|
|||||||
history_to_insert = []
|
history_to_insert = []
|
||||||
objects_to_update = []
|
objects_to_update = []
|
||||||
|
|
||||||
|
# only generate events that we want to be notified on (we only need to do this once as all plugObj have the same prefix)
|
||||||
|
statuses_to_report_on = get_setting_value(pluginPref + "_REPORT_ON")
|
||||||
|
|
||||||
for plugObj in pluginObjects:
|
for plugObj in pluginObjects:
|
||||||
# keep old createdTime time if the plugObj already was created before
|
# keep old createdTime time if the plugObj already was created before
|
||||||
@@ -500,10 +502,7 @@ def process_plugin_events(db, plugin, pluginsState, plugEventsArr):
|
|||||||
if plugObj.status == 'new':
|
if plugObj.status == 'new':
|
||||||
objects_to_insert.append(values)
|
objects_to_insert.append(values)
|
||||||
else:
|
else:
|
||||||
objects_to_update.append(values + (plugObj.index,)) # Include index for UPDATE
|
objects_to_update.append(values + (plugObj.index,)) # Include index for UPDATE
|
||||||
|
|
||||||
# only generate events that we want to be notified on
|
|
||||||
statuses_to_report_on = get_setting_value(plugObj.pluginPref + "_REPORT_ON")
|
|
||||||
|
|
||||||
if plugObj.status in statuses_to_report_on:
|
if plugObj.status in statuses_to_report_on:
|
||||||
events_to_insert.append(values)
|
events_to_insert.append(values)
|
||||||
|
|||||||
Reference in New Issue
Block a user