Improve instruction
[edumed.git] / wtem / management / commands / wtem_email_teachers.py
1 # -*- coding: utf-8 -*-
2
3 import sys
4 from optparse import make_option
5
6 from django.core.management.base import BaseCommand, CommandError
7 from django.conf import settings
8 from django.core.mail import send_mail
9 from django.template.loader import render_to_string
10
11 from contact.models import Contact
12
13
14 class Command(BaseCommand):
15     def handle(self, *args, **options):
16         sent = 0
17         failed = 0
18
19         query = Contact.objects.filter(form_tag = 'wtem').order_by('contact').distinct('contact')
20         template_name = args[0]
21         message = render_to_string('wtem/' + template_name + '.txt')
22         subject = render_to_string('wtem/' + template_name + '_subject.txt')
23         
24         answer = raw_input('Send the following to %d teachers with subject "%s"\n\n %s\n\n?' % \
25             (query.count(), subject.encode('utf8'), message.encode('utf8')))
26
27         if answer == 'yes':
28             for contact in query:
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(
43             subject,
44             message,
45             getattr(settings, 'WTEM_CONTACT_EMAIL', 'no-reply@edukacjamedialna.edu.pl'),
46             [email],
47             fail_silently=False
48         )
49