sendNotifications: Use django send_mail function, add some error handling
This commit is contained in:
parent
dc82bfc58a
commit
7cdf6e961f
@ -1,6 +1,3 @@
|
|||||||
import smtplib
|
|
||||||
|
|
||||||
from email.message import EmailMessage
|
|
||||||
from itertools import groupby
|
from itertools import groupby
|
||||||
|
|
||||||
from django.core.mail import send_mail
|
from django.core.mail import send_mail
|
||||||
@ -13,16 +10,6 @@ from tasks.models import Tool, Task, Event, Reminder
|
|||||||
class Command(BaseCommand):
|
class Command(BaseCommand):
|
||||||
help = 'Sends any notifications for upcoming and overdue tasks'
|
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):
|
def _active_reminders(self):
|
||||||
for reminder in Reminder.objects.all():
|
for reminder in Reminder.objects.all():
|
||||||
if reminder.should_remind:
|
if reminder.should_remind:
|
||||||
@ -37,10 +24,23 @@ class Command(BaseCommand):
|
|||||||
}
|
}
|
||||||
|
|
||||||
for user, reminders in reminders_per_user.items():
|
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(
|
self.stdout.write(self.style.SUCCESS(
|
||||||
f'Sending notification for {len(reminders)} task(s) to {user}'))
|
f'Sending notification for {len(reminders)} task(s) to {user}'))
|
||||||
|
|
||||||
self._send_email(
|
try:
|
||||||
user.email,
|
send_mail(
|
||||||
f'[CMS Tool Maintenance] {len(reminders)} tasks are upcoming or overdue!',
|
subject=f'[CMS Tool Maintenance] {len(reminders)} tasks are upcoming or overdue!',
|
||||||
template.render({'reminders': reminders}).strip())
|
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}"))
|
||||||
|
Loading…
Reference in New Issue
Block a user