From 7cdf6e961f2d8a64ee819e2fb177f8a83868efe7 Mon Sep 17 00:00:00 2001 From: Adam Goldsmith Date: Tue, 8 Dec 2020 16:03:19 -0500 Subject: [PATCH] sendNotifications: Use django send_mail function, add some error handling --- .../management/commands/sendNotifications.py | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/tasks/management/commands/sendNotifications.py b/tasks/management/commands/sendNotifications.py index d5648bc..dd114b8 100644 --- a/tasks/management/commands/sendNotifications.py +++ b/tasks/management/commands/sendNotifications.py @@ -1,6 +1,3 @@ -import smtplib - -from email.message import EmailMessage from itertools import groupby from django.core.mail import send_mail @@ -13,16 +10,6 @@ from tasks.models import Tool, Task, Event, Reminder class Command(BaseCommand): help = 'Sends any notifications for upcoming and overdue tasks' - def _send_email(self, to, subject, content): - msg = EmailMessage() - msg.set_content(content) - msg['Subject'] = subject - msg['From'] = 'adam@adamgoldsmith.name' - msg['To'] = to - - with smtplib.SMTP("localhost") as server: - server.send_message(msg) - def _active_reminders(self): for reminder in Reminder.objects.all(): if reminder.should_remind: @@ -37,10 +24,23 @@ class Command(BaseCommand): } for user, reminders in reminders_per_user.items(): + if not user.email: + self.stdout.write(self.style.ERROR( + f"Can't send email, user '{user}' is missing an email address")) + continue + self.stdout.write(self.style.SUCCESS( f'Sending notification for {len(reminders)} task(s) to {user}')) - self._send_email( - user.email, - f'[CMS Tool Maintenance] {len(reminders)} tasks are upcoming or overdue!', - template.render({'reminders': reminders}).strip()) + try: + send_mail( + subject=f'[CMS Tool Maintenance] {len(reminders)} tasks are upcoming or overdue!', + message=template.render({'reminders': reminders}).strip(), + from_email='adam@adamgoldsmith.name', + recipient_list=[user.email], + fail_silently=False + ) + + except Exception as e: + self.stdout.write(self.style.ERROR( + f"Failed to send mail for user '{user}': {type(e).__name__}: {e}"))