Files
classifieds/app/services/email.py
T
2026-06-15 11:23:05 -04:00

35 lines
1.1 KiB
Python

"""Email service. Sends via SMTP relay (Brevo); falls back to console log in dev."""
import smtplib
from email.message import EmailMessage
from flask import current_app
def send_email(to_addr: str, subject: str, body: str) -> bool:
cfg = current_app.config
server = cfg.get("MAIL_SERVER")
# Dev fallback: no SMTP configured -> log to console.
if not server:
current_app.logger.info(
"[DEV EMAIL] to=%s subject=%s\n%s", to_addr, subject, body
)
return True
msg = EmailMessage()
msg["From"] = f"{cfg.get('MAIL_FROM_NAME')} <{cfg.get('MAIL_FROM')}>"
msg["To"] = to_addr
msg["Subject"] = subject
msg.set_content(body)
try:
with smtplib.SMTP(server, cfg.get("MAIL_PORT", 587), timeout=15) as s:
if cfg.get("MAIL_USE_TLS"):
s.starttls()
if cfg.get("MAIL_USERNAME"):
s.login(cfg.get("MAIL_USERNAME"), cfg.get("MAIL_PASSWORD"))
s.send_message(msg)
return True
except Exception as exc: # noqa: BLE001
current_app.logger.error("Email send failed: %s", exc)
return False