Files
get_ovh_bills/mail.py

76 lines
2.3 KiB
Python

import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
logger = logging.getLogger("ovh_factures.fetcher")
def _as_header(value) -> str:
# Convertit en chaîne pour les en-têtes MIME; join pour listes/tuples.
if isinstance(value, (list, tuple, set)):
return ", ".join(map(str, value))
return str(value)
def _as_rcpt_list(value):
# Liste de destinataires pour SMTP
if value is None:
return []
if isinstance(value, (list, tuple, set)):
return [str(v) for v in value]
return [str(value)]
def construct_html(bills: list[tuple[str, str]]) -> str:
try:
rows = [
f"<li><b style='color:#2c3e50;'>Facture n°{b}</b> — "
f"<span style='color:#16a085;'>émise le {d}</span></li>"
for b, d in bills
]
return f"""<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Nouvelle(s) facture(s)</title></head>
<body style="font-family:Arial, sans-serif;background:#f9f9f9;color:#333;">
<div style="max-width:600px;margin:auto;padding:20px;background:#fff;border:1px solid #ddd;border-radius:8px;">
<h2 style="color:#e74c3c;text-align:center;">
Vous avez reçu <b>{len(bills)}</b> nouvelle(s) facture(s)
</h2>
<ul style="line-height:1.6;font-size:14px;">{"".join(rows)}</ul>
</div>
</body>
</html>"""
except Exception as e:
logger.exception("Erreur dans construct_html", e)
return ""
def send_email(
subject,
content,
email_from,
email_password,
smtp_mail_address,
smpt_port,
email_to,
on_error=None,
):
try:
msg = MIMEMultipart()
msg["From"] = _as_header(email_from)
msg["To"] = _as_header(email_to)
msg["Subject"] = _as_header(subject)
msg.attach(MIMEText(str(content), "html"))
rcpts = _as_rcpt_list(email_to)
with smtplib.SMTP(smtp_mail_address, smpt_port) as server:
server.starttls()
server.login(str(email_from), str(email_password))
server.sendmail(str(email_from), rcpts, msg.as_string())
except Exception as e:
logger.exception("Erreur dans send_email")
if on_error:
on_error(e)