from time import sleep from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.encoding import smart_str from .models import Subscriber, MailingStatus class SendShit(): def __init__(self, newsletter, mailing, verbose=0): self.verbose = verbose self.newsletter = newsletter self.mailing = mailing all_subscribers = Subscriber.objects.filter(newsletter=self.newsletter,subscribed=True,unsubscribed=False).values('email_field') already_sent = MailingStatus.objects.filter(newsletter_mailing=self.mailing,status=1).values('subscriber__email_field') self.subscribers = all_subscribers.difference(already_sent) def send_mailings(self): mailings = len(self.subscribers) print("mailing newsletter to %s subscribers"%mailings) i = 1 for s in self.subscribers: subscriber = Subscriber.objects.get(newsletter=self.newsletter,email_field=s['email_field'],subscribed=True,unsubscribed=False) status = None if self.verbose == 1: print("mailing newsletter %s of %s to %s" %(i,mailings,subscriber)) status, created = MailingStatus.objects.get_or_create( newsletter_mailing=self.mailing, subscriber=subscriber, ) # New instance, try sending if created: email = self.build_message(subscriber) status.status=1 if self.verbose==1: print("successfully sent %s the newsletter mailing %s"%(subscriber, self.mailing)) status.save() else: # not new, check if error and resend or just continue if status.status == 2: if self.verbose==1: print("retrying error") try: email = self.build_message(subscriber) status.status=1 if self.verbose==1: print("successfully sent %s the newsletter mailing %s"%(subscriber, self.mailing)) except: status.status=2 if self.verbose == 1: print("failed to send %s to %s"%(self.mailing, subscriber)) status.save() i=i+1 sleep(2) def build_message(self, subscriber): """ Build the email as plain text with a a multipart alternative for HTML """ subject = smart_str("%s: %s — %s" %(self.mailing.newsletter.title, self.mailing.get_issue_str(), self.mailing.title)) from_email, to = 'Scott Gilbertson ', subscriber.get_email() text_content = render_to_string(self.newsletter.get_template_plain(), {'object': self.mailing, 'subscriber':subscriber}) html_content = render_to_string(self.newsletter.get_template_html(), {'object': self.mailing, 'subscriber':subscriber}) #print(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") #msg.Header.Add('List-Unsubscribe', '' % subscriber.unsubscribe_activate_url) msg.send() ''' for header, value in self.newsletter.server.custom_headers.items(): message[header] = value ''' return msg