2020-06-15 00:02:39 +00:00
|
|
|
import logging
|
2020-04-30 07:43:10 +00:00
|
|
|
from smtplib import SMTPException
|
2020-06-12 04:24:24 +00:00
|
|
|
from threading import Thread
|
2020-04-30 07:43:10 +00:00
|
|
|
|
|
|
|
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-04-30 07:43:10 +00:00
|
|
|
|
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
|
|
|
|
2020-04-30 07:43:10 +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):
|
|
|
|
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()
|
|
|
|
|
2020-04-30 07:43:10 +00:00
|
|
|
|
|
|
|
class SMTPEmailBackend(BaseEmailBackend):
|
2020-06-12 04:24:24 +00:00
|
|
|
def send_campaign(self, request, campaign, contacts):
|
2020-04-30 07:43:10 +00:00
|
|
|
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-04-30 07:43:10 +00:00
|
|
|
|
2020-06-15 00:02:39 +00:00
|
|
|
safe_campaign = Campaign.objects.select_for_update().get(pk=campaign.pk)
|
|
|
|
# safe_contacts = Contact.objects.select_for_update().filter(id_in=)
|
|
|
|
campaign_thread = SendCampaignThread(safe_campaign, messages, contacts)
|
2020-06-12 04:24:24 +00:00
|
|
|
campaign_thread.start()
|