| 1 | """
|
|---|
| 2 | Email-sending.
|
|---|
| 3 |
|
|---|
| 4 | """
|
|---|
| 5 | from django.core.mail import EmailMultiAlternatives
|
|---|
| 6 | from django.template.loader import render_to_string
|
|---|
| 7 | from django.conf import settings
|
|---|
| 8 |
|
|---|
| 9 |
|
|---|
| 10 |
|
|---|
| 11 | def send_templated_multipart(template_name, context, recipients,
|
|---|
| 12 | sender=None, fail_silently=False):
|
|---|
| 13 | """
|
|---|
| 14 | Send a templated multi-part e-mail with both HTML and text parts.
|
|---|
| 15 |
|
|---|
| 16 | ``template_name`` should not include an extension. Both HTML (``.html``)
|
|---|
| 17 | and text (``.txt``) versions must exist, as well as ``.subject.txt`` for
|
|---|
| 18 | the subject. For example, 'emails/public_submit' will use
|
|---|
| 19 | ``public_submit.html``, ``public_submit.txt``, and
|
|---|
| 20 | ``public_submit.subject.txt``.
|
|---|
| 21 |
|
|---|
| 22 | ``context`` should be a dictionary; all three templates (HTML,
|
|---|
| 23 | text, and subject) are rendered with this same context.
|
|---|
| 24 |
|
|---|
| 25 | Other arguments are the same as the ``send_multipart`` function in this
|
|---|
| 26 | module.
|
|---|
| 27 |
|
|---|
| 28 | """
|
|---|
| 29 | text_part = render_to_string('%s.txt' % template_name, context)
|
|---|
| 30 | html_part = render_to_string('%s.html' % template_name, context)
|
|---|
| 31 | subject = render_to_string('%s.subject.txt' % template_name, context)
|
|---|
| 32 |
|
|---|
| 33 | return send_multipart(
|
|---|
| 34 | subject, text_part, html_part, recipients, sender, fail_silently)
|
|---|
| 35 |
|
|---|
| 36 |
|
|---|
| 37 |
|
|---|
| 38 |
|
|---|
| 39 | def send_multipart(subject, text_part, html_part, recipients,
|
|---|
| 40 | sender=None, fail_silently=False):
|
|---|
| 41 | """
|
|---|
| 42 | Send a multi-part email with both HTML and text parts.
|
|---|
| 43 |
|
|---|
| 44 | ``subject`` should be the email subject as a string (newlines will be
|
|---|
| 45 | replaced with spaces).
|
|---|
| 46 |
|
|---|
| 47 | ``text_part`` and ``html_part`` should be text and HTML versions of the
|
|---|
| 48 | email body, as strings.
|
|---|
| 49 |
|
|---|
| 50 | ``recipients`` should be a list of email addresses.
|
|---|
| 51 |
|
|---|
| 52 | ``sender`` can be an email, 'Name <email>' or None. If unspecified, the
|
|---|
| 53 | ``DEFAULT_FROM_EMAIL`` setting will be used.
|
|---|
| 54 |
|
|---|
| 55 | """
|
|---|
| 56 | sender = sender or settings.DEFAULT_FROM_EMAIL
|
|---|
| 57 |
|
|---|
| 58 | # collapse newlines in subject to spaces
|
|---|
| 59 | subject = u" ".join(subject.splitlines()).strip()
|
|---|
| 60 | msg = EmailMultiAlternatives(subject, text_part, sender, recipients)
|
|---|
| 61 | msg.attach_alternative(html_part, "text/html")
|
|---|
| 62 | return msg.send(fail_silently)
|
|---|