1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import send_mass_mail
from django.utils import timezone
from django.template import Context, loader
from django.conf import settings
from edt.models import Group, Subscription, Course
from edt.utils import get_week, group_courses
import datetime
class Command(BaseCommand):
help = "Sends emails to subscribed users"
def handle(self, *args, **options):
year, week, day = timezone.now().isocalendar()
if day >= 6:
year, week, _ = (timezone.now() + datetime.timedelta(weeks=1)).isocalendar()
start, end = get_week(year, week)
subscriptions = Subscription.objects.filter(active=True)
content = {}
mails = []
print("Generating messages...")
for subscription in subscriptions:
if subscription.group.id not in content:
courses = Course.objects.get_courses_for_group(subscription.group, begin__gte=start, begin__lt=end)
grouped_courses = group_courses(courses)
template = loader.get_template("timetable_email.txt")
context = Context({"subscription": subscription, "courses": grouped_courses, "week": week})
content[subscription.group.id] = template.render(context)
footer = loader.get_template("mail_footer.txt")
context = Context({"admins": settings.ADMINS, "token": subscription.token})
mail_content = content[subscription.group.id] + footer.render(context)
mails.append(("{0} - {1} - Semaine {2}".format(subscription.group.timetable.name, subscription.group.name, week), mail_content, settings.DEFAULT_FROM_EMAIL, [subscription.email],))
print("Sending mails...")
send_mass_mail(mails)
self.stdout.write(self.style.SUCCESS("Done."))
|