"""Outbound notifications for public-site events.""" import logging from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.urls import reverse from leads.models import Lead from public.email_branding import email_brand_context logger = logging.getLogger(__name__) def notify_admins_of_contact_form(lead: Lead) -> bool: """ Email CONTACT_EMAIL when someone submits the public contact form. Returns True if a message was sent. Failures are logged; callers should not block the visitor success path on delivery errors. """ to_email = (settings.CONTACT_EMAIL or "").strip() if not to_email: logger.warning("CONTACT_EMAIL unset; skipping contact-form notification") return False contact = lead.contact name = contact.full_name or "(no name)" phone = contact.phone or "(none)" email = contact.email or "(none)" message = (lead.message or "").strip() or "(no message)" site = (settings.PUBLIC_SITE_URL or "").rstrip("/") portal_path = reverse("leads:detail", kwargs={"pk": lead.pk}) portal_url = f"{site}{portal_path}" if site else portal_path postal = contact.postal_address or {} address_bits = [ postal.get("line1") or "", postal.get("line2") or "", ", ".join( part for part in [ postal.get("city") or "", postal.get("state") or "", postal.get("zip") or "", ] if part ), ] address = "\n".join(bit for bit in address_bits if bit) or "(none)" ctx = email_brand_context( name=name, email=email, phone=phone, address=address, message=message, portal_url=portal_url, ) text_content = get_template("emails/contact_email.txt").render(ctx) html_content = get_template("emails/contact_email.html").render(ctx) mail = EmailMultiAlternatives( subject=f"New contact form inquiry from {name}", body=text_content, from_email=settings.DEFAULT_FROM_EMAIL, to=[to_email], reply_to=[contact.email] if contact.email else None, ) mail.attach_alternative(html_content, "text/html") try: mail.send(fail_silently=False) except Exception: logger.exception("Failed to send contact-form notification to %s", to_email) return False return True