88 lines
3.7 KiB
Python
88 lines
3.7 KiB
Python
"""Envío de notificaciones por email usando smtplib nativo."""
|
|
import os
|
|
import smtplib
|
|
import logging
|
|
from email.mime.multipart import MIMEMultipart
|
|
from email.mime.text import MIMEText
|
|
from email.utils import formatdate
|
|
|
|
logger = logging.getLogger("collina.email")
|
|
|
|
SMTP_HOST = os.environ.get("SMTP_HOST", "")
|
|
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587"))
|
|
SMTP_USER = os.environ.get("SMTP_USER", "")
|
|
SMTP_PASS = os.environ.get("SMTP_PASS", "")
|
|
NOTIFY_TO = os.environ.get("NOTIFY_TO", "")
|
|
DASHBOARD_URL = os.environ.get("DASHBOARD_URL", "https://forms.collinasystems.com.mx/dashboard")
|
|
|
|
|
|
def _render_value(value) -> str:
|
|
"""Convierte un valor del JSON de respuesta a HTML legible."""
|
|
if isinstance(value, list):
|
|
rows = []
|
|
for item in value:
|
|
if isinstance(item, dict):
|
|
parts = [f"{k}: {v}" for k, v in item.items()]
|
|
rows.append(" — ".join(parts))
|
|
else:
|
|
rows.append(str(item))
|
|
return "<br>".join(rows) if rows else "<em>(vacío)</em>"
|
|
if isinstance(value, dict):
|
|
return "<br>".join(f"{k}: {v}" for k, v in value.items())
|
|
if value in (None, ""):
|
|
return "<em>(vacío)</em>"
|
|
return str(value)
|
|
|
|
|
|
def _build_html(label: str, data: dict) -> str:
|
|
rows = ""
|
|
for key, value in data.items():
|
|
rows += f"""
|
|
<tr>
|
|
<td style="padding:10px 14px;border-bottom:1px solid #eee;font-weight:600;color:#1c1c1e;vertical-align:top;white-space:nowrap;">{key}</td>
|
|
<td style="padding:10px 14px;border-bottom:1px solid #eee;color:#3a3a3c;">{_render_value(value)}</td>
|
|
</tr>"""
|
|
|
|
return f"""<!DOCTYPE html>
|
|
<html>
|
|
<body style="margin:0;padding:24px;background:#f2f2f7;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;">
|
|
<div style="max-width:600px;margin:0 auto;background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 4px 24px rgba(0,0,0,0.08);">
|
|
<div style="background:linear-gradient(135deg,#0A84FF,#409CFF);padding:24px 28px;">
|
|
<div style="color:#fff;font-size:13px;letter-spacing:2px;opacity:0.85;">COLLINA FORMS</div>
|
|
<div style="color:#fff;font-size:20px;font-weight:700;margin-top:4px;">Nueva respuesta recibida</div>
|
|
<div style="color:#fff;font-size:15px;opacity:0.9;margin-top:2px;">{label}</div>
|
|
</div>
|
|
<table style="width:100%;border-collapse:collapse;font-size:14px;">
|
|
{rows}
|
|
</table>
|
|
<div style="padding:20px 28px;background:#fafafa;text-align:center;">
|
|
<a href="{DASHBOARD_URL}" style="display:inline-block;background:#0A84FF;color:#fff;text-decoration:none;padding:10px 22px;border-radius:10px;font-weight:600;font-size:14px;">Ver en el dashboard</a>
|
|
</div>
|
|
</div>
|
|
</body>
|
|
</html>"""
|
|
|
|
|
|
def send_new_response_email(label: str, data: dict) -> None:
|
|
"""Envía el email de notificación. Nunca propaga errores SMTP."""
|
|
if not (SMTP_HOST and SMTP_USER and NOTIFY_TO):
|
|
logger.info("SMTP no configurado; se omite el envío de email.")
|
|
return
|
|
|
|
try:
|
|
msg = MIMEMultipart("alternative")
|
|
msg["Subject"] = f"[Collina Forms] Nueva respuesta — {label}"
|
|
msg["From"] = SMTP_USER
|
|
msg["To"] = NOTIFY_TO
|
|
msg["Date"] = formatdate(localtime=True)
|
|
msg.attach(MIMEText(_build_html(label, data), "html", "utf-8"))
|
|
|
|
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=15) as server:
|
|
server.ehlo()
|
|
server.starttls()
|
|
server.login(SMTP_USER, SMTP_PASS)
|
|
server.sendmail(SMTP_USER, [NOTIFY_TO], msg.as_string())
|
|
logger.info("Email de notificación enviado a %s", NOTIFY_TO)
|
|
except Exception as exc: # noqa: BLE001 — nunca romper el flujo
|
|
logger.error("Fallo al enviar email de notificación: %s", exc)
|