wagtail-birdsong/birdsong/backends/smtp.py

56 lines
1.8 KiB
Python
Raw Normal View History

from smtplib import SMTPException
2020-06-12 04:24:24 +00:00
from threading import Thread
from django.core.mail import send_mass_mail
from django.template.loader import render_to_string
2020-06-12 04:24:24 +00:00
from django.utils import timezone
2020-06-12 04:24:24 +00:00
from birdsong.models import CampaignStatus
2020-05-01 00:48:00 +00:00
from birdsong.utils import send_mass_html_mail
2020-06-12 04:24:24 +00:00
import logging
from . import BaseEmailBackend
2020-06-12 04:24:24 +00:00
logger = logging.getLogger(__name__)
class SendCampaignThread(Thread):
def __init__(self, campaign, messages, contacts):
super().__init__()
self.campaign = campaign
self.messages = messages
self.contacts = contacts
def run(self):
try:
logger.info(f"Sending {len(self.messages)} emails")
send_mass_html_mail(self.messages)
logger.info(f"Emails finsihed sending")
self.campaign.status = CampaignStatus.SENT
self.campaign.sent_date = timezone.now()
self.campaign.create_receipts(self.contacts)
except SMTPException as e:
logger.exception(f"Problem sending campaign: {self.campaign}")
self.campaign.status = CampaignStatus.FAILED
self.campaign.save()
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-12 04:24:24 +00:00
campaign_thread = SendCampaignThread(campaign, messages, contacts)
campaign_thread.start()