Fix campaign stuck on sending under async queue, and stop UUID ValidationError when SMTP2GO tests send "Headers Unavailable".
59 lines
2.2 KiB
Python
59 lines
2.2 KiB
Python
"""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
|
|
from public.email_branding import email_brand_context, plain_text_to_email_html
|
|
|
|
# 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 ""
|
|
)
|
|
|
|
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=body,
|
|
content_html=plain_text_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}"
|