cmsmanage/tasks/management/commands/sendNotifications.py

47 lines
1.5 KiB
Python

import smtplib
from email.message import EmailMessage
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 _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:
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():
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())