sendNotifications: Use django send_mail function, add some error handling

This commit is contained in:
Adam Goldsmith 2020-12-08 16:03:19 -05:00
parent dc82bfc58a
commit 7cdf6e961f

View File

@ -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}"))