39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
# notify.py
|
|
import os, smtplib
|
|
from email.mime.text import MIMEText
|
|
from email.utils import formataddr
|
|
from dotenv import load_dotenv
|
|
|
|
# load .env automatically (ENV_FILE can override path)
|
|
load_dotenv(os.getenv("ENV_FILE", ".env"))
|
|
|
|
def send_email(subject: str, body_text: str, to_addr: str | None = None):
|
|
if os.getenv("MAIL_ENABLED", "false").lower() != "true":
|
|
print("[notify] MAIL_ENABLED != true; skipping email")
|
|
return
|
|
|
|
smtp_host = os.getenv("SMTP_HOST")
|
|
smtp_port = int(os.getenv("SMTP_PORT", "587"))
|
|
smtp_user = os.getenv("SMTP_USER")
|
|
smtp_pass = os.getenv("SMTP_PASS")
|
|
mail_from = os.getenv("MAIL_FROM") or smtp_user
|
|
mail_to = to_addr or os.getenv("MAIL_TO")
|
|
|
|
if not (smtp_host and smtp_user and smtp_pass and mail_to):
|
|
print("[notify] missing SMTP config; skipping email")
|
|
return
|
|
|
|
msg = MIMEText(body_text, "plain", "utf-8")
|
|
msg["Subject"] = subject
|
|
msg["From"] = formataddr(("Intesa Logs Agent", mail_from))
|
|
msg["To"] = mail_to
|
|
|
|
with smtplib.SMTP(smtp_host, smtp_port, timeout=20) as s:
|
|
try:
|
|
s.starttls()
|
|
except smtplib.SMTPException:
|
|
pass
|
|
s.login(smtp_user, smtp_pass)
|
|
s.send_message(msg)
|
|
print(f"[notify] sent email to {mail_to}")
|