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