dceb8315b62ffb25b78792183259d66533d8cf8f
[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 contact.models import Contact
7 from stage2.models import Participant
8 from wtem.management.commands import send_mail
9
10
11 class Command(BaseCommand):
12     def handle(self, *args, **options):
13         sent = 0
14         failed = 0
15
16         query = Participant.objects.order_by('contact__contact').distinct('contact__contact')\
17             .values_list('contact__contact', flat=True)
18         template_name = args[0]
19         message = render_to_string('wtem/' + template_name + '.txt')
20         subject = render_to_string('wtem/' + template_name + '_subject.txt')
21         
22         answer = raw_input(
23             'Send the following to %d teachers with subject "%s"\n\n %s\n\n?' %
24             (query.count(), subject.encode('utf8'), message.encode('utf8')))
25
26         if answer == 'yes':
27             for contact in query:
28                 try:
29                     self.send_message(message, subject, contact)
30                 except Exception as e:
31                     failed += 1
32                     self.stdout.write('failed sending to: ' + contact + ' - ' + str(e))
33                 else:
34                     sent += 1
35                     self.stdout.write('message sent to: ' + contact)
36
37         self.stdout.write('sent: %s, failed: %s' % (sent, failed))
38
39     def send_message(self, message, subject, email):
40         self.stdout.write('>>> sending to %s' % email)
41         send_mail(subject=subject, body=message, to=[email])
42