cmsmanage/tasks/management/commands/sendNotifications.py

47 lines
1.7 KiB
Python

from itertools import groupby
from django.core.mail import send_mail
from django.core.management.base import BaseCommand, CommandError
from django.template import loader
from tasks.models import Tool, Task, Event, Reminder
class Command(BaseCommand):
help = 'Sends any notifications for upcoming and overdue tasks'
def _active_reminders(self):
for reminder in Reminder.objects.all():
if reminder.should_remind:
yield reminder
def handle(self, *args, **options):
template = loader.get_template('tasks/notificationEmail.txt')
reminders_per_user = {
user: sorted(reminders, key=lambda r: r.task.next_recurrence)
for user, reminders in groupby(self._active_reminders(), lambda r: r.user)
}
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}'))
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}"))