bc0b4d84336d95f835f31b6dc1a8a6cb34b22914
[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 xerxes.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', 1)
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         if (field == 'From'):
40             from_email = value
41         elif (field == 'Subject'):
42             subject = value
43         else:
44             # Don't put From and Subject in the dict, else they'll be
45             # present twice.
46             headers_dict[field] = value
47
48     msg = EmailMessage(
49         # Only setting the From address through headers won't set the
50         # envelope address right.
51         from_email = from_email,
52         subject    = subject,
53         body       = body, 
54         to         = addresses, 
55         headers    = headers_dict
56     )
57     msg.send()
58 # vim: set sts=4 sw=4 expandtab: