Niveau configurable via LOG_LEVEL (défaut DEBUG). Les erreurs de config JSON invalide remontent maintenant un message clair (fichier + position) au lieu d'un JSONDecodeError brut.
42 lines
1.5 KiB
Python
42 lines
1.5 KiB
Python
"""Mail delivery via a configured SMTP relay (host/port/credentials in config.json)."""
|
|
import logging
|
|
import smtplib
|
|
from email.mime.text import MIMEText
|
|
|
|
logger = logging.getLogger("pointeuse.mail")
|
|
|
|
|
|
def send_mail(to_addr: str, subject: str, body: str, from_addr: str, smtp_cfg: dict):
|
|
host = smtp_cfg.get("host")
|
|
if not host:
|
|
logger.error("envoi annulé: aucun serveur SMTP configuré (smtp.host manquant dans config.json)")
|
|
raise RuntimeError("Aucun serveur SMTP configuré (smtp.host manquant dans config.json).")
|
|
port = int(smtp_cfg.get("port", 587))
|
|
user = smtp_cfg.get("user")
|
|
password = smtp_cfg.get("password")
|
|
use_tls = smtp_cfg.get("use_tls", True)
|
|
|
|
msg = MIMEText(body)
|
|
msg["Subject"] = subject
|
|
msg["From"] = from_addr
|
|
msg["To"] = to_addr
|
|
|
|
logger.info(
|
|
"envoi mail: to=%r from=%r subject=%r via smtp=%s:%s user=%r tls=%r",
|
|
to_addr, from_addr, subject, host, port, user, use_tls,
|
|
)
|
|
try:
|
|
with smtplib.SMTP(host, port, timeout=10) as smtp:
|
|
smtp.set_debuglevel(1)
|
|
if use_tls:
|
|
logger.debug("STARTTLS vers %s:%s", host, port)
|
|
smtp.starttls()
|
|
if user:
|
|
logger.debug("login SMTP en tant que %r", user)
|
|
smtp.login(user, password)
|
|
smtp.send_message(msg)
|
|
logger.info("mail envoyé avec succès à %r", to_addr)
|
|
except Exception:
|
|
logger.exception("échec de l'envoi du mail à %r via %s:%s", to_addr, host, port)
|
|
raise
|