* Add notify.py that can email a given template to given recipients (Users/Groups...
[matthijs/projects/xerxes.git] / tools / notify.py
1 from django.contrib.auth.models import User,Group
2 from django.core.mail import EmailMessage
3 from django.template import loader
4 from ee.tools.misc import make_iter
5
6 """
7 Notify someone about something.
8 """
9 def notify(recipients, template, context = {}):
10     recipients = make_iter(recipients)
11     addresses = []; 
12     for r in recipients:
13         if (isinstance(r, User)):
14             addresses.append(r.email)
15         elif (isinstance(r, Group)):
16             addresses += [m.email for m in r.user_set.all()]
17         else:
18             # Assume it is an email address
19             addresses.append(r)
20     # TODO: Make addresses unique
21
22     context['recipients'] = recipients 
23     context['addresses'] = addresses 
24
25     rendered = loader.render_to_string(template, context)
26     (headers, body) = rendered.split('\n\n', 2)
27
28     # Turn the headers into a dict so EmailMessage can turn them into a
29     # string again. Bit pointless, but it works. 
30     # Perhaps we should just use python email stuff directly. OTOH, we
31     # still always need to parse for the From header.
32
33     headers_dict = {}
34     # If no From header is present, let EmailMessage do the default
35     # thing
36     from_email = None
37     for header in headers.split('\n'):
38         (field, value) = header.split(':')
39         headers_dict[field] = value
40         if (field == 'From'):
41             from_email = value
42
43     msg = EmailMessage(
44         # Only setting the From address through headers won't set the
45         # envelope address right.
46         from_email = from_email,
47         body       = body, 
48         to         = addresses, 
49         headers    = headers_dict
50     )
51     msg.send()