"""SMTP2GO email via Django's SMTP backend (mail.smtp2go.com).""" from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from contacts.models import Channel from messaging.services import one_click_unsubscribe_url, preferences_url, render_merge_tags from public.email_branding import ( campaign_body_to_email_html, campaign_body_to_plain_text, email_brand_context, ) # Reported back on SMTP2GO webhooks when this header is selected in webhook settings. MONICA_MESSAGE_HEADER = "X-Monica-Message-Id" def send_email(message) -> str: contact = message.contact if not contact.email: raise ValueError("Contact has no email address") campaign = message.campaign subject = campaign.subject_override or ( campaign.template.subject if campaign.template else "Message from Monica" ) body = message.body_snapshot or campaign.body_override or ( campaign.template.body if campaign.template else "" ) subject = render_merge_tags(subject, contact) body = render_merge_tags(body, contact) site = (settings.PUBLIC_SITE_URL or "").rstrip("/") prefs_path = preferences_url(str(contact.pk), Channel.EMAIL) one_click_path = one_click_unsubscribe_url(str(contact.pk), Channel.EMAIL) prefs_url = f"{site}{prefs_path}" if site else prefs_path one_click_url = f"{site}{one_click_path}" if site else one_click_path ctx = email_brand_context( title=subject, content=campaign_body_to_plain_text(body), content_html=campaign_body_to_email_html(body), prefs_url=prefs_url, one_click_url=one_click_url, ) text_content = get_template("emails/marketing_email.txt").render(ctx) html_content = get_template("emails/marketing_email.html").render(ctx) email = EmailMultiAlternatives( subject=subject, body=text_content, from_email=settings.DEFAULT_FROM_EMAIL, to=[contact.email], headers={ "List-Unsubscribe": f"<{one_click_url}>", "List-Unsubscribe-Post": "List-Unsubscribe=One-Click", MONICA_MESSAGE_HEADER: str(message.pk), }, ) email.attach_alternative(html_content, "text/html") email.send(fail_silently=False) # Placeholder until SMTP2GO webhook supplies the real email_id. return f"smtp-{message.pk}"