new format of cwiczenie wybor
[edumed.git] / wtem / management / commands / wtem_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 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 = Contact.objects.filter(form_tag='wtem').order_by('contact').distinct('contact')
16         template_name = args[0]
17         message = render_to_string('wtem/' + template_name + '.txt')
18         subject = render_to_string('wtem/' + template_name + '_subject.txt')
19         
20         answer = raw_input(
21             'Send the following to %d teachers with subject "%s"\n\n %s\n\n?' %
22             (query.count(), subject.encode('utf8'), message.encode('utf8')))
23
24         if answer == 'yes':
25             for contact in query:
26                 try:
27                     self.send_message(message, subject, contact.contact)
28                 except Exception as e:
29                     failed += 1
30                     self.stdout.write('failed sending to: ' + contact.contact + ' - ' + str(e))
31                 else:
32                     sent += 1
33                     self.stdout.write('message sent to: ' + contact.contact)
34
35         self.stdout.write('sent: %s, failed: %s' % (sent, failed))
36
37     def send_message(self, message, subject, email):
38         self.stdout.write('>>> sending to %s' % email)
39         send_mail(subject=subject, body=message, to=[email])
40