wagtail-birdsong/birdsong/backends/smtp.py

65 lines
2.1 KiB
Python
Raw Normal View History

2020-06-15 00:02:39 +00:00
import logging
from smtplib import SMTPException
2020-06-12 04:24:24 +00:00
from threading import Thread
from django.db import close_old_connections, transaction
from django.template.loader import render_to_string
2020-06-12 04:24:24 +00:00
from django.utils import timezone
2020-06-15 00:02:39 +00:00
from birdsong.models import Campaign, CampaignStatus, Contact
2020-05-01 00:48:00 +00:00
from birdsong.utils import send_mass_html_mail
2020-06-15 00:02:39 +00:00
from . import BaseEmailBackend
2020-06-12 04:24:24 +00:00
logger = logging.getLogger(__name__)
2020-06-15 00:02:39 +00:00
2020-06-12 04:24:24 +00:00
class SendCampaignThread(Thread):
2020-06-15 04:20:55 +00:00
def __init__(self, campaign_pk, contact_pks, messages):
2020-06-12 04:24:24 +00:00
super().__init__()
2020-06-15 04:20:55 +00:00
self.campaign_pk = campaign_pk
self.contact_pks = contact_pks
2020-06-12 04:24:24 +00:00
self.messages = messages
def run(self):
try:
logger.info(f"Sending {len(self.messages)} emails")
send_mass_html_mail(self.messages)
2020-06-15 05:47:52 +00:00
logger.info("Emails finished sending")
2020-06-15 04:20:55 +00:00
with transaction.atomic():
Campaign.objects.filter(pk=self.campaign_pk).update(
2020-06-15 04:20:55 +00:00
status=CampaignStatus.SENT,
sent_date=timezone.now(),
)
2020-06-15 05:47:52 +00:00
fresh_contacts = Contact.objects.filter(
pk__in=self.contact_pks)
Campaign.objects.get(
pk=self.campaign_pk).receipts.add(*fresh_contacts)
except SMTPException:
logger.exception(f"Problem sending campaign: {self.campaign_pk}")
2020-06-12 04:24:24 +00:00
self.campaign.status = CampaignStatus.FAILED
finally:
close_old_connections()
2020-06-12 04:24:24 +00:00
class SMTPEmailBackend(BaseEmailBackend):
2020-06-12 04:24:24 +00:00
def send_campaign(self, request, campaign, contacts):
messages = []
for contact in contacts:
content = render_to_string(
campaign.get_template(request),
campaign.get_context(request, contact),
)
2020-05-19 01:29:14 +00:00
messages.append({
2020-06-12 04:24:24 +00:00
'subject': campaign.subject,
2020-05-19 01:29:14 +00:00
'body': content,
'from_email': self.from_email,
'to': [contact.email],
'reply_to': [self.reply_to],
})
2020-06-15 05:47:52 +00:00
campaign_thread = SendCampaignThread(
campaign.pk, [c.pk for c in contacts], messages)
2020-06-12 04:24:24 +00:00
campaign_thread.start()