From: Matthijs Kooijman Date: Thu, 31 Jan 2008 17:22:12 +0000 (+0100) Subject: * Add notify.py that can email a given template to given recipients (Users/Groups... X-Git-Url: https://git.stderr.nl/gitweb?a=commitdiff_plain;h=63cf915b35fb1270e9cc99fcb42804d16bea1a7e;p=matthijs%2Fprojects%2Fxerxes.git * Add notify.py that can email a given template to given recipients (Users/Groups/addresses). --- diff --git a/tools/notify.py b/tools/notify.py new file mode 100644 index 0000000..4530255 --- /dev/null +++ b/tools/notify.py @@ -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()