From e9ef398b6a972e26c673c41b935d2b694a903e6c Mon Sep 17 00:00:00 2001 From: Zak Timson Date: Fri, 15 Sep 2017 16:30:20 -0400 Subject: [PATCH] Added email command --- .../management/commands/sendnewsletters.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 newsletters/management/commands/sendnewsletters.py diff --git a/newsletters/management/commands/sendnewsletters.py b/newsletters/management/commands/sendnewsletters.py new file mode 100644 index 0000000..fc31135 --- /dev/null +++ b/newsletters/management/commands/sendnewsletters.py @@ -0,0 +1,24 @@ +from django.db.models import Q +from django.core import mail +from django.core.management.base import BaseCommand +from django.utils import timezone +from django.utils.html import strip_tags + +from OACPL import settings +from newsletters.models import Newsletter, Subscriber + + +class Command(BaseCommand): + help = 'Send out newsletter emails to subscribers' + + def handle(self, *args, **options): + newsletters = Newsletter.objects.filter(Q(sent=False) & Q(publish__lte=timezone.now())) + subscribers = Subscriber.objects.all().values_list('email', flat=True) + print(f'Found {len(newsletters)} unsent newsletters') + print(f'Found {len(subscribers)} subscribers') + for newsletter in newsletters: + print(f'Sending newsletter: "{newsletter.subject}"') + mail.send_mail(newsletter.subject, strip_tags(newsletter.body), settings.EMAIL_HOST_USER, subscribers, html_message=newsletter.body) + newsletter.sent = True + newsletter.save() + print('Complete!')