fix email to teachers (don't send to None)
[edumed.git] / stage2 / management / commands / stage2_email_teachers.py
1 # -*- coding: utf-8 -*-
2
3 from django.core.management.base import BaseCommand
4 from django.template.loader import render_to_string
5
6 from stage2.models import Participant
7 from wtem.management.commands import send_mail
8
9
10 class Command(BaseCommand):
11     def handle(self, *args, **options):
12         sent = 0
13         failed = 0
14
15         query = Participant.objects.exclude(contact=None).order_by('contact__contact').distinct('contact__contact')\
16             .values_list('contact__contact', flat=True)
17         template_name = args[0]
18         message = render_to_string('stage2/' + template_name + '.txt')
19         subject = render_to_string('stage2/' + template_name + '_subject.txt')
20         
21         answer = raw_input(
22             'Send the following to %d teachers with subject "%s"\n\n %s\n\n?' %
23             (query.count(), subject.encode('utf8'), message.encode('utf8')))
24
25         if answer == 'yes':
26             for contact in query:
27                 try:
28                     self.send_message(message, subject, contact)
29                 except Exception as e:
30                     failed += 1
31                     self.stdout.write('failed sending to: ' + contact + ' - ' + str(e))
32                 else:
33                     sent += 1
34                     self.stdout.write('message sent to: ' + contact)
35
36         self.stdout.write('sent: %s, failed: %s' % (sent, failed))
37
38     def send_message(self, message, subject, email):
39         self.stdout.write('>>> sending to %s' % email)
40         send_mail(subject=subject, body=message, to=[email])
41