Notification rework - SMTP v0.2 - WIP👷‍♂️

This commit is contained in:
Jokob-sk
2023-10-08 22:00:24 +11:00
parent e4a64a11bd
commit 1e693abfc4
7 changed files with 740 additions and 550 deletions

View File

@@ -504,25 +504,13 @@
"Email_icon" : "<i class=\"fa fa-at\"></i>",
"REPORT_MAIL_name" : "Enable email",
"REPORT_MAIL_description" : "If enabled an email is sent out with a list of changes you nove subscribed to. Please also fill out all remaining settings related to the SMTP setup below. If facing issues, set <code>LOG_LEVEL</code> to <code>debug</code> and check the <a href=\"/maintenance.php#tab_Logging\">error log</a>.",
"SMTP_SERVER_name" : "SMTP server URL",
"SMTP_SERVER_description" : "The SMTP server host URL. For example <code>smtp-relay.sendinblue.com</code>. To use Gmail as an SMTP server <a target=\"_blank\" href=\"https://github.com/jokob-sk/Pi.Alert/blob/main/docs/SMTP.md\">follow this guide</a>",
"SMTP_PORT_name" : "SMTP server PORT",
"SMTP_PORT_description" : "Port number used for the SMTP connection. Set to <code>0</code> if you do not want to use a port when connecting to the SMTP server.",
"SMTP_SKIP_LOGIN_name" : "Skip authentication",
"SMTP_SKIP_LOGIN_description" : "Do not use authentication when connecting to the SMTP server.",
"SMTP_USER_name" : "SMTP user",
"SMTP_USER_description" : "The user name used to login into the SMTP server (sometimes a full email address).",
"SMTP_PASS_name" : "SMTP password",
"SMTP_PASS_description" : "The SMTP server password. ",
"SMTP_SKIP_TLS_name" : "Do not use TLS",
"SMTP_SKIP_TLS_description" : "Disable TLS when connecting to your SMTP server.",
"SMTP_FORCE_SSL_name" : "Force SSL",
"SMTP_FORCE_SSL_description" : "Force SSL when connecting to your SMTP server.",
"SYSTEM_TITLE" : "System Information",
"REPORT_TO_name" : "Send email to",
"REPORT_TO_description" : "Email address to which the notification will be send to.",
"REPORT_FROM_name" : "Email subject",
"REPORT_FROM_description" : "Notification email subject line. Some SMTP servers need this to be an email.",
"REPORT_TO_name" : "deprecated",
"REPORT_TO_description" : "deprecated",
"REPORT_FROM_name" : "deprecated",
"REPORT_FROM_description" : "deprecated",
"Webhooks_display_name" : "Webhooks",
"Webhooks_icon" : "<i class=\"fa fa-circle-nodes\"></i>",
"REPORT_WEBHOOK_name" : "Enable Webhooks",

View File

@@ -1,33 +1,38 @@
{
"code_name": "_publisher_apprise",
"code_name": "_publisher_email",
"unique_prefix": "SMTP",
"enabled": true,
"data_source": "script",
"show_ui": true,
"localized": ["display_name", "description", "icon"],
"localized": [
"display_name",
"description",
"icon"
],
"display_name": [
{
"language_code": "en_us",
"string" : "Apprise publisher"
"string": "Email publisher (SMTP)"
},
{
"language_code": "es_es",
"string" : "Habilitar Apprise"
"string": "Habilitar email (SMTP)"
}
],
"icon":[{
"icon": [
{
"language_code": "en_us",
"string" : "<i class=\"fa-solid fa-bullhorn\"></i>"
}],
"string": "<i class=\"fa-solid fa-at\"></i>"
}
],
"description": [
{
"language_code": "en_us",
"string" : "A plugin to publish a notification via the Apprise gateway."
"string": "A plugin to publish a notification via Email (SMTP) gateway."
}
],
"params": [],
"database_column_definitions":
[
"database_column_definitions": [
{
"column": "Index",
"css_classes": "col-sm-2",
@@ -35,15 +40,19 @@
"type": "label",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "N/A"
},
{
"language_code": "es_es",
"string": "N/A"
}]
}
]
},
{
"column": "Plugin",
@@ -52,15 +61,19 @@
"type": "label",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "N/A"
},
{
"language_code": "es_es",
"string": "N/A"
}]
}
]
},
{
"column": "Object_PrimaryID",
@@ -69,11 +82,15 @@
"type": "url",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "N/A"
}]
}
]
},
{
"column": "Object_SecondaryID",
@@ -82,15 +99,19 @@
"type": "label",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "N/A"
},
{
"language_code": "es_es",
"string": "N/A"
}]
}
]
},
{
"column": "DateTimeCreated",
@@ -99,11 +120,15 @@
"type": "label",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "Sent when"
}]
}
]
},
{
"column": "DateTimeChanged",
@@ -112,15 +137,19 @@
"type": "label",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "Changed"
},
{
"language_code": "es_es",
"string": "Cambiado"
}]
}
]
},
{
"column": "Watched_Value1",
@@ -129,11 +158,15 @@
"type": "label",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "Notification GUID"
}]
}
]
},
{
"column": "Watched_Value2",
@@ -142,11 +175,15 @@
"type": "textarea_readonly",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "Result"
}]
}
]
},
{
"column": "Watched_Value3",
@@ -155,15 +192,19 @@
"type": "label",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "N/A"
},
{
"language_code": "es_es",
"string": "N/A"
}]
}
]
},
{
"column": "Watched_Value4",
@@ -172,15 +213,19 @@
"type": "label",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "N/A"
},
{
"language_code": "es_es",
"string": "N/A"
}]
}
]
},
{
"column": "UserData",
@@ -189,15 +234,19 @@
"type": "textbox_save",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "Comments"
},
{
"language_code": "es_es",
"string": "Comentarios"
}]
}
]
},
{
"column": "Status",
@@ -223,15 +272,19 @@
"replacement": "<div style='text-align:center'><i class='fa-solid fa-question'></i></div>"
}
],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "Status"
},
{
"language_code": "es_es",
"string": "Estado"
}]
}
]
},
{
"column": "Extra",
@@ -240,41 +293,55 @@
"type": "label",
"default_value": "",
"options": [],
"localized": ["name"],
"name":[{
"localized": [
"name"
],
"name": [
{
"language_code": "en_us",
"string": "Extra"
},
{
"language_code": "es_es",
"string": "Extra"
}]
}
]
}
],
"settings": [
{
"function": "RUN",
"events": ["test"],
"events": [
"test"
],
"type": "text.select",
"default_value": "disabled",
"options": ["disabled", "on_notification" ],
"localized": ["name", "description"],
"name" :[{
"options": [
"disabled",
"on_notification"
],
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "When to run"
},
{
"language_code": "es_es",
"string": "Cuando ejecuta"
}],
}
],
"description": [
{
"language_code": "en_us",
"string" : "Enable sending notifications via <a target=\"_blank\" href=\"https://hub.docker.com/r/caronc/apprise\">Apprise</a>."
"string": "Enable sending notifications via the Email (SMTP) gateway."
},
{
"language_code": "es_es",
"string" : "Habilitar el envío de notificaciones a través de <a target=\"_blank\" href=\"https://hub.docker.com/r/caronc/apprise\">Apprise</a>."
"string": "Si está habilitado, se envía un correo electrónico con una lista de cambios a los que se ha suscrito. Complete también todas las configuraciones restantes relacionadas con la configuración de SMTP a continuación"
}
]
},
@@ -283,31 +350,42 @@
"type": "readonly",
"default_value": "python3 /home/pi/pialert/front/plugins/_publisher_email/email.py",
"options": [],
"localized": ["name", "description"],
"name" : [{
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "Command"
},
{
"language_code": "es_es",
"string": "Comando"
}],
"description": [{
}
],
"description": [
{
"language_code": "en_us",
"string": "Command to run"
},
{
"language_code": "es_es",
"string": "Comando a ejecutar"
}]
}
]
},
{
"function": "RUN_TIMEOUT",
"type": "integer",
"default_value": 10,
"default_value": 20,
"options": [],
"localized": ["name", "description"],
"name" : [{
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "Run timeout"
},
@@ -318,107 +396,288 @@
{
"language_code": "de_de",
"string": "Wartezeit"
}],
"description": [{
}
],
"description": [
{
"language_code": "en_us",
"string": "Maximum time in seconds to wait for the script to finish. If this time is exceeded the script is aborted."
},
{
"language_code": "es_es",
"string": "Tiempo máximo en segundos para esperar a que finalice el script. Si se supera este tiempo, el script se cancela."
}]
}
]
},
{
"function": "HOST",
"function": "SERVER",
"type": "text",
"default_value": "",
"options": [],
"localized": ["name", "description"],
"name" : [{
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string" : "Apprise host URL"
"string": "SMTP server URL"
},
{
"language_code": "es_es",
"string" : "URL del host de Apprise"
}],
"description": [{
"string": "URL del servidor SMTP"
}
],
"description": [
{
"language_code": "en_us",
"string" : "Apprise host URL starting with <code>http://</code> or <code>https://</code>. (do not forget to include <code>/notify</code> at the end)"
"string": "The SMTP server host URL. For example <code>smtp-relay.sendinblue.com</code>. To use Gmail as an SMTP server <a target=\"_blank\" href=\"https://github.com/jokob-sk/Pi.Alert/blob/main/docs/SMTP.md\">follow this guide</a>"
},
{
"language_code": "es_es",
"string" : "URL del host de Apprise que comienza con <code>http://</code> o <code>https://</code>. (no olvide incluir <code>/notify</code> al final)"
}]
"string": "La URL del host del servidor SMTP. Por ejemplo, <code>smtp-relay.sendinblue.com</code>. Para utilizar Gmail como servidor SMTP <a target=\"_blank\" href=\"https://github.com/jokob-sk/Pi.Alert/blob/main/docs/SMTP.md\">siga esta guía</a >"
}
]
},
{
"function": "URL",
"type": "text",
"default_value": "",
"options": [],
"localized": ["name", "description"],
"name" : [{
"language_code": "en_us",
"string" : "Apprise notification URL"
},
{
"language_code": "es_es",
"string" : "URL de notificación de Apprise"
}],
"description": [{
"language_code": "en_us",
"string" : "Apprise notification target URL. For example for Telegram it would be <code>tgram://{bot_token}/{chat_id}</code>."
},
{
"language_code": "es_es",
"string" : "Informar de la URL de destino de la notificación. Por ejemplo, para Telegram sería <code>tgram://{bot_token}/{chat_id}</code>."
}]
},
{
"function": "PAYLOAD",
"type": "text.select",
"default_value": "html",
"options": ["html", "text"],
"localized": ["name", "description"],
"name" : [{
"language_code": "en_us",
"string" : "Payload type"
},
{
"language_code": "es_es",
"string" : "Tipo de carga"
}],
"description": [{
"language_code": "en_us",
"string" : "Select the payoad type sent to Apprise. For example <code>html</code> works well with emails, <code>text</code> with chat apps, such as Telegram."
},
{
"language_code": "es_es",
"string" : "Seleccione el tipo de carga útil enviada a Apprise. Por ejemplo, <code>html</code> funciona bien con correos electrónicos, <code>text</code> con aplicaciones de chat, como Telegram."
}]
},
{
"function": "SIZE",
"function": "PORT",
"type": "integer",
"default_value": 1024,
"default_value": 587,
"options": [],
"localized": ["name", "description"],
"name" : [{
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string" : "Max payload size"
"string": "SMTP server PORT"
},
{
"language_code": "es_es",
"string" : "Tamaño máximo de carga útil"
}],
"description": [{
"string": "Puerto del servidor SMTP"
}
],
"description": [
{
"language_code": "en_us",
"string" : "The maximum size of the apprise payload as number of characters in the passed string. If above limit, it will be truncated and a <code>(text was truncated)</code> message is appended."
"string": "Port number used for the SMTP connection. Set to <code>0</code> if you do not want to use a port when connecting to the SMTP server."
},
{
"language_code": "es_es",
"string" : "El tamaño máximo de la carga útil de información como número de caracteres en la cadena pasada. Si supera el límite, se truncará y se agregará un mensaje <code>(text was truncated)</code>."
}]
"string": "Número de puerto utilizado para la conexión SMTP. Establézcalo en <code>0</code> si no desea utilizar un puerto al conectarse al servidor SMTP."
}
]
},
{
"function": "SKIP_LOGIN",
"type": "boolean",
"default_value": false,
"options": [],
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "Skip authentication"
},
{
"language_code": "es_es",
"string": "Omitir autenticación"
}
],
"description": [
{
"language_code": "en_us",
"string": "Do not use authentication when connecting to the SMTP server."
},
{
"language_code": "es_es",
"string": "No utilice la autenticación cuando se conecte al servidor SMTP."
}
]
},
{
"function": "USER",
"type": "text",
"default_value": "",
"options": [],
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "SMTP user"
},
{
"language_code": "es_es",
"string": "Nombre de usuario SMTP"
}
],
"description": [
{
"language_code": "en_us",
"string": "The user name used to login into the SMTP server (sometimes a full email address)."
},
{
"language_code": "es_es",
"string": "El nombre de usuario utilizado para iniciar sesión en el servidor SMTP (a veces, una dirección de correo electrónico completa)."
}
]
},
{
"function": "PASS",
"type": "password",
"default_value": "",
"options": [],
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "SMTP password"
},
{
"language_code": "es_es",
"string": "Contraseña de SMTP"
}
],
"description": [
{
"language_code": "en_us",
"string": "The SMTP server password."
},
{
"language_code": "es_es",
"string": "La contraseña del servidor SMTP."
}
]
},
{
"function": "SKIP_TLS",
"type": "boolean",
"default_value": false,
"options": [],
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "Do not use TLS"
},
{
"language_code": "es_es",
"string": "No usar TLS"
}
],
"description": [
{
"language_code": "en_us",
"string": "Disable TLS when connecting to your SMTP server."
},
{
"language_code": "es_es",
"string": "Deshabilite TLS cuando se conecte a su servidor SMTP."
}
]
},
{
"function": "FORCE_SSL",
"type": "boolean",
"default_value": false,
"options": [],
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "Force SSL"
},
{
"language_code": "es_es",
"string": "Forzar SSL"
}
],
"description": [
{
"language_code": "en_us",
"string": "Force SSL when connecting to your SMTP server."
},
{
"language_code": "es_es",
"string": "Forzar SSL al conectarse a su servidor SMTP"
}
]
},
{
"function": "REPORT_TO",
"type": "text",
"default_value": "user@gmail.com",
"options": [],
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "Send email to"
},
{
"language_code": "es_es",
"string": "Enviar el email a"
}
],
"description": [
{
"language_code": "en_us",
"string": "Email address to which the notification will be send to."
},
{
"language_code": "es_es",
"string": "Dirección de correo electrónico a la que se enviará la notificación."
}
]
},
{
"function": "REPORT_FROM",
"type": "text",
"default_value": "Pi.Alert <user@gmail.com>",
"options": [],
"localized": [
"name",
"description"
],
"name": [
{
"language_code": "en_us",
"string": "Email subject"
},
{
"language_code": "es_es",
"string": "Asunto del email"
}
],
"description": [
{
"language_code": "en_us",
"string": "Notification email subject line. Some SMTP servers need this to be an email."
},
{
"language_code": "es_es",
"string": "Asunto del correo electrónico de notificación."
}
]
}
]
}

View File

@@ -1 +0,0 @@
This plugin will not be loaded

View File

@@ -6,6 +6,9 @@ from cron_converter import Cron
from pathlib import Path
import datetime
import json
import shutil
import re
import conf
from const import fullConfPath
@@ -62,6 +65,9 @@ def importConfigs (db):
# Only import file if the file was modifed since last import.
# this avoids time zone issues as we just compare the previous timestamp to the current time stamp
# rename settings that have changed names due to code cleanup and migration to plugins
renameSettings(config_file)
fileModifiedTime = os.path.getmtime(config_file)
mylog('debug', ['[Import Config] checking config file '])
@@ -114,18 +120,6 @@ def importConfigs (db):
# Notification gateways
# ----------------------------------------
# Email
conf.REPORT_MAIL = ccd('REPORT_MAIL', False , c_d, 'Enable email', 'boolean', '', 'Email', ['test'])
conf.SMTP_SERVER = ccd('SMTP_SERVER', '' , c_d,'SMTP server URL', 'text', '', 'Email')
conf.SMTP_PORT = ccd('SMTP_PORT', 587 , c_d, 'SMTP port', 'integer', '', 'Email')
conf.REPORT_TO = ccd('REPORT_TO', 'user@gmail.com' , c_d, 'Email to', 'text', '', 'Email')
conf.REPORT_FROM = ccd('REPORT_FROM', 'Pi.Alert <user@gmail.com>' , c_d, 'Email Subject', 'text', '', 'Email')
conf.SMTP_SKIP_LOGIN = ccd('SMTP_SKIP_LOGIN', False , c_d, 'SMTP skip login', 'boolean', '', 'Email')
conf.SMTP_USER = ccd('SMTP_USER', '' , c_d, 'SMTP user', 'text', '', 'Email')
conf.SMTP_PASS = ccd('SMTP_PASS', '' , c_d, 'SMTP password', 'password', '', 'Email')
conf.SMTP_SKIP_TLS = ccd('SMTP_SKIP_TLS', False , c_d, 'SMTP skip TLS', 'boolean', '', 'Email')
conf.SMTP_FORCE_SSL = ccd('SMTP_FORCE_SSL', False , c_d, 'Force SSL', 'boolean', '', 'Email')
# Webhooks
conf.REPORT_WEBHOOK = ccd('REPORT_WEBHOOK', False , c_d, 'Enable Webhooks', 'boolean', '', 'Webhooks', ['test'])
conf.WEBHOOK_URL = ccd('WEBHOOK_URL', '' , c_d, 'Target URL', 'text', '', 'Webhooks')
@@ -284,3 +278,55 @@ def read_config_file(filename):
confDict = {} # config dictionary
exec(code, {"__builtins__": {}}, confDict)
return confDict
#-------------------------------------------------------------------------------
replacements = {
r'\bREPORT_TO\b': 'SMTP_REPORT_TO',
r'\bREPORT_FROM\b': 'SMTP_REPORT_FROM'
}
def renameSettings(config_file):
# Check if the file contains any of the old setting code names
contains_old_settings = False
# Open the original config_file for reading
with open(str(config_file), 'r') as original_file: # Convert config_file to a string
for line in original_file:
# Use regular expressions with word boundaries to check for the old setting code names
if any(re.search(key, line) for key in replacements.keys()):
contains_old_settings = True
break # Exit the loop if any old setting is found
# If the file contains old settings, proceed with renaming and backup
if contains_old_settings:
# Create a backup file with the suffix "_old_setting_names" and timestamp
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
backup_file = f"{config_file}_old_setting_names_{timestamp}.bak"
mylog('debug', f'[Config] Old setting names will be replaced and a backup ({backup_file}) of the config created.')
shutil.copy(str(config_file), backup_file) # Convert config_file to a string
# Open the original config_file for reading and create a temporary file for writing
with open(str(config_file), 'r') as original_file, open(str(config_file) + "_temp", 'w') as temp_file: # Convert config_file to a string
for line in original_file:
# Use regular expressions with word boundaries for replacements
for key, value in replacements.items():
line = re.sub(key, value, line)
# Write the modified line to the temporary file
temp_file.write(line)
# Close both files
original_file.close()
temp_file.close()
# Replace the original config_file with the temporary file
shutil.move(str(config_file) + "_temp", str(config_file)) # Convert config_file to a string
else:
mylog('debug', '[Config] No old setting names found in the file. No changes made.')

View File

@@ -1,100 +0,0 @@
""" Pi.Alert module to send notification emails """
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import conf
import socket
from helper import hide_email, noti_obj
from logger import mylog, print_log
#-------------------------------------------------------------------------------
def check_config ():
if conf.SMTP_SERVER == '' or conf.REPORT_FROM == '' or conf.REPORT_TO == '':
mylog('none', ['[Email Check Config] Error: Email service not set up correctly. Check your pialert.conf SMTP_*, REPORT_FROM and REPORT_TO variables.'])
return False
else:
return True
#-------------------------------------------------------------------------------
def send (msg: noti_obj):
pText = msg.text
pHTML = msg.html
mylog('debug', '[Send Email] REPORT_TO: ' + hide_email(str(conf.REPORT_TO)) + ' SMTP_USER: ' + hide_email(str(conf.SMTP_USER)))
# Compose email
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Pi.Alert Report'
msg['From'] = conf.REPORT_FROM
msg['To'] = conf.REPORT_TO
msg.attach (MIMEText (pText, 'plain'))
msg.attach (MIMEText (pHTML, 'html'))
failedAt = ''
failedAt = print_log ('SMTP try')
try:
# Send mail
failedAt = print_log('Trying to open connection to ' + str(conf.SMTP_SERVER) + ':' + str(conf.SMTP_PORT))
# Set a timeout for the SMTP connection (in seconds)
smtp_timeout = 30
if conf.SMTP_FORCE_SSL:
failedAt = print_log('SMTP_FORCE_SSL == True so using .SMTP_SSL()')
if conf.SMTP_PORT == 0:
failedAt = print_log('SMTP_PORT == 0 so sending .SMTP_SSL(SMTP_SERVER)')
smtp_connection = smtplib.SMTP_SSL(conf.SMTP_SERVER)
else:
failedAt = print_log('SMTP_PORT == 0 so sending .SMTP_SSL(SMTP_SERVER, SMTP_PORT)')
smtp_connection = smtplib.SMTP_SSL(conf.SMTP_SERVER, conf.SMTP_PORT, timeout=smtp_timeout)
else:
failedAt = print_log('SMTP_FORCE_SSL == False so using .SMTP()')
if conf.SMTP_PORT == 0:
failedAt = print_log('SMTP_PORT == 0 so sending .SMTP(SMTP_SERVER)')
smtp_connection = smtplib.SMTP (conf.SMTP_SERVER)
else:
failedAt = print_log('SMTP_PORT == 0 so sending .SMTP(SMTP_SERVER, SMTP_PORT)')
smtp_connection = smtplib.SMTP (conf.SMTP_SERVER, conf.SMTP_PORT)
failedAt = print_log('Setting SMTP debug level')
# Log level set to debug of the communication between SMTP server and client
if conf.LOG_LEVEL == 'debug':
smtp_connection.set_debuglevel(1)
failedAt = print_log( 'Sending .ehlo()')
smtp_connection.ehlo()
if not conf.SMTP_SKIP_TLS:
failedAt = print_log('SMTP_SKIP_TLS == False so sending .starttls()')
smtp_connection.starttls()
failedAt = print_log('SMTP_SKIP_TLS == False so sending .ehlo()')
smtp_connection.ehlo()
if not conf.SMTP_SKIP_LOGIN:
failedAt = print_log('SMTP_SKIP_LOGIN == False so sending .login()')
smtp_connection.login (conf.SMTP_USER, conf.SMTP_PASS)
failedAt = print_log('Sending .sendmail()')
smtp_connection.sendmail (conf.REPORT_FROM, conf.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', '[Send Email] Last executed - ' + str(failedAt))

View File

@@ -24,8 +24,6 @@ from const import pialertPath, logPath, apiPath
from helper import noti_obj, generate_mac_links, removeDuplicateNewLines, timeNowTZ, hide_email, updateState, get_file_content, write_file
from logger import logResult, mylog, print_log
from publishers.email import (check_config as email_check_config,
send as send_email )
from publishers.ntfy import (check_config as ntfy_check_config,
send as send_ntfy )
from publishers.webhook import (check_config as webhook_check_config,