Interface web Flask securisee pour surveiller CPU, RAM, disques et processus (JVM, Nginx, Amadea Web 8 x64). Alertes email SMTP configurables, seuils reglables, compilation PyInstaller en .exe, installation service Windows via NSSM. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
82 lines
2.9 KiB
Python
82 lines
2.9 KiB
Python
"""Envoi d'alertes par email via SMTP."""
|
|
|
|
import smtplib
|
|
from email.mime.text import MIMEText
|
|
from email.mime.multipart import MIMEMultipart
|
|
|
|
|
|
class EmailAlerter:
|
|
def __init__(self, config_manager):
|
|
self.config = config_manager
|
|
|
|
def _get_smtp_config(self):
|
|
return self.config.get("smtp", {})
|
|
|
|
def is_configured(self):
|
|
smtp = self._get_smtp_config()
|
|
return bool(smtp.get("server") and smtp.get("from_email") and smtp.get("to_emails"))
|
|
|
|
def send_alert(self, subject, body):
|
|
"""Envoie un email d'alerte. Silencieux si SMTP non configure."""
|
|
if not self.is_configured():
|
|
return False, "SMTP non configure"
|
|
return self._send_email(subject, body)
|
|
|
|
def send_test(self):
|
|
"""Envoie un email de test pour valider la configuration SMTP."""
|
|
if not self.is_configured():
|
|
return False, "Configuration SMTP incomplete"
|
|
subject = "[TEST] Supervision - Test de configuration email"
|
|
body = (
|
|
"Ceci est un email de test.\n\n"
|
|
"Si vous recevez ce message, la configuration SMTP est correcte.\n\n"
|
|
"-- Supervision"
|
|
)
|
|
return self._send_email(subject, body)
|
|
|
|
def _send_email(self, subject, body):
|
|
smtp_cfg = self._get_smtp_config()
|
|
try:
|
|
msg = MIMEMultipart()
|
|
msg["From"] = smtp_cfg["from_email"]
|
|
msg["To"] = ", ".join(smtp_cfg["to_emails"])
|
|
msg["Subject"] = subject
|
|
msg.attach(MIMEText(body, "plain", "utf-8"))
|
|
|
|
server_addr = smtp_cfg["server"]
|
|
port = int(smtp_cfg.get("port", 587))
|
|
use_tls = smtp_cfg.get("use_tls", True)
|
|
|
|
if use_tls:
|
|
server = smtplib.SMTP(server_addr, port, timeout=15)
|
|
server.ehlo()
|
|
server.starttls()
|
|
server.ehlo()
|
|
else:
|
|
server = smtplib.SMTP(server_addr, port, timeout=15)
|
|
server.ehlo()
|
|
|
|
username = smtp_cfg.get("username", "")
|
|
password = smtp_cfg.get("password", "")
|
|
if username and password:
|
|
server.login(username, password)
|
|
|
|
server.sendmail(
|
|
smtp_cfg["from_email"],
|
|
smtp_cfg["to_emails"],
|
|
msg.as_string(),
|
|
)
|
|
server.quit()
|
|
return True, "Email envoye avec succes"
|
|
|
|
except smtplib.SMTPAuthenticationError:
|
|
return False, "Erreur d'authentification SMTP (identifiants incorrects)"
|
|
except smtplib.SMTPConnectError:
|
|
return False, f"Impossible de se connecter au serveur SMTP {server_addr}:{port}"
|
|
except smtplib.SMTPRecipientsRefused:
|
|
return False, "Destinataire(s) refuse(s) par le serveur"
|
|
except TimeoutError:
|
|
return False, f"Timeout de connexion vers {server_addr}:{port}"
|
|
except Exception as e:
|
|
return False, f"Erreur SMTP: {str(e)}"
|