* Add notify.py that can email a given template to given recipients (Users/Groups...
authorMatthijs Kooijman <matthijs@stdin.nl>
Thu, 31 Jan 2008 17:22:12 +0000 (18:22 +0100)
committerMatthijs Kooijman <matthijs@stdin.nl>
Thu, 31 Jan 2008 17:22:12 +0000 (18:22 +0100)
tools/notify.py [new file with mode: 0644]

diff --git a/tools/notify.py b/tools/notify.py
new file mode 100644 (file)
index 0000000..4530255
--- /dev/null
@@ -0,0 +1,51 @@
+from django.contrib.auth.models import User,Group
+from django.core.mail import EmailMessage
+from django.template import loader
+from ee.tools.misc import make_iter
+
+"""
+Notify someone about something.
+"""
+def notify(recipients, template, context = {}):
+    recipients = make_iter(recipients)
+    addresses = []; 
+    for r in recipients:
+        if (isinstance(r, User)):
+            addresses.append(r.email)
+        elif (isinstance(r, Group)):
+            addresses += [m.email for m in r.user_set.all()]
+        else:
+            # Assume it is an email address
+            addresses.append(r)
+    # TODO: Make addresses unique
+
+    context['recipients'] = recipients 
+    context['addresses'] = addresses 
+
+    rendered = loader.render_to_string(template, context)
+    (headers, body) = rendered.split('\n\n', 2)
+
+    # Turn the headers into a dict so EmailMessage can turn them into a
+    # string again. Bit pointless, but it works. 
+    # Perhaps we should just use python email stuff directly. OTOH, we
+    # still always need to parse for the From header.
+
+    headers_dict = {}
+    # If no From header is present, let EmailMessage do the default
+    # thing
+    from_email = None
+    for header in headers.split('\n'):
+        (field, value) = header.split(':')
+        headers_dict[field] = value
+        if (field == 'From'):
+            from_email = value
+
+    msg = EmailMessage(
+        # Only setting the From address through headers won't set the
+        # envelope address right.
+        from_email = from_email,
+        body       = body, 
+        to         = addresses, 
+        headers    = headers_dict
+    )
+    msg.send()