Skip to content
This repository has been archived by the owner on Jul 20, 2020. It is now read-only.

Latest commit

 

History

History
354 lines (226 loc) · 11.9 KB

sending_mail.rst

File metadata and controls

354 lines (226 loc) · 11.9 KB

Sending Mail

Djrill handles all outgoing email sent through Django's standard django.core.mail package, including ~django.core.mail.send_mail, ~django.core.mail.send_mass_mail, the ~django.core.mail.EmailMessage class, and even ~django.core.mail.mail_admins.

If you'd like to selectively send only some messages through Mandrill, there is a way to use multiple email backends <multiple-backends>.

Django Email Support

Djrill supports most of the functionality of Django's ~django.core.mail.EmailMessage and ~django.core.mail.EmailMultiAlternatives classes.

Some notes and limitations:

Display Names

All email addresses (from, to, cc, bcc) can be simple ("email@example.com") or can include a display name ("Real Name <email@example.com>").

CC and BCC Recipients

Djrill properly identifies "cc" and "bcc" recipients to Mandrill.

Note that you may need to set the Mandrill option preserve_recipients to !True if you want recipients to be able to see who else was included in the "to" list.

0.9 Previously, Djrill (and Mandrill) didn't distinguish "cc" from "to", and allowed only a single "bcc" recipient.

HTML/Alternative Parts

To include an HTML version of a message, use ~django.core.mail.EmailMultiAlternatives.attach_alternative:

from django.core.mail import EmailMultiAlternatives

msg = EmailMultiAlternatives("Subject", "text body",
                             "from@example.com", ["to@example.com"])
msg.attach_alternative("<html>html body</html>", "text/html")

Djrill allows a maximum of one ~django.core.mail.EmailMultiAlternatives.attach_alternative on a message, and it must be mimetype="text/html". Otherwise, Djrill will raise ~djrill.NotSupportedByMandrillError when you attempt to send the message. (Mandrill doesn't support sending multiple html alternative parts, or any non-html alternatives.)

Attachments

Djrill will send a message's attachments. (Note that Mandrill may impose limits on size and type of attachments.)

Also, if an image attachment has a Content-ID header, Djrill will tell Mandrill to treat that as an embedded image rather than an ordinary attachment. (For an example, see ~DjrillBackendTests.test_embedded_images in tests/test_mandrill_send.py.)

0.3 Attachments

0.4 Special handling for embedded images

Headers

Djrill accepts additional headers and passes them along to Mandrill:

msg = EmailMessage( ...
    headers={'Reply-To': "reply@example.com", 'List-Unsubscribe': "..."}
)

0.9 In earlier versions, Djrill only allowed Reply-To and X-* headers, matching previous Mandrill API restrictions.

1.4 Djrill also supports the reply_to param added to ~django.core.mail.EmailMessage in Django 1.8. (If you provide both a 'Reply-To' header and the reply_to param, the header will take precedence.)

Mandrill-Specific Options

Most of the options from the Mandrill messages/send API message struct can be set directly on an ~django.core.mail.EmailMessage (or subclass) object:

important

Boolean: whether Mandrill should send this message ahead of non-important ones.

0.7

track_opens

Boolean: whether Mandrill should enable open-tracking for this message. Default from your Mandrill account settings. :

message.track_opens = True

track_clicks

Boolean: whether Mandrill should enable click-tracking for this message. Default from your Mandrill account settings.

Note

Mandrill has an option to track clicks in HTML email but not plaintext, but it's only available in your Mandrill account settings. If you want to use that option, set it at Mandrill, and don't set the track_clicks attribute here.

auto_text

Boolean: whether Mandrill should automatically generate a text body from the HTML. Default from your Mandrill account settings.

auto_html

Boolean: whether Mandrill should automatically generate an HTML body from the plaintext. Default from your Mandrill account settings.

inline_css

Boolean: whether Mandrill should inline CSS styles in the HTML. Default from your Mandrill account settings.

0.4

url_strip_qs

Boolean: whether Mandrill should ignore any query parameters when aggregating URL tracking data. Default from your Mandrill account settings.

preserve_recipients

Boolean: whether Mandrill should include all recipients in the "to" message header. Default from your Mandrill account settings.

view_content_link

Boolean: set False on sensitive messages to instruct Mandrill not to log the content.

0.7

tracking_domain

str: domain Mandrill should use to rewrite tracked links and host tracking pixels for this message. Useful if you send email from multiple domains. Default from your Mandrill account settings.

signing_domain

str: domain Mandrill should use for DKIM signing and SPF on this message. Useful if you send email from multiple domains. Default from your Mandrill account settings.

return_path_domain

str: domain Mandrill should use for the message's return-path.

0.7

merge_language

str: the merge tag language if using merge tags -- e.g., "mailchimp" or "handlebars". Default from your Mandrill account settings.

1.3

global_merge_vars

dict: merge variables to use for all recipients (most useful with mandrill-templates). :

message.global_merge_vars = {'company': "ACME", 'offer': "10% off"}

Merge data must be strings or other JSON-serializable types. (See formatting-merge-data for details.)

merge_vars

dict: per-recipient merge variables (most useful with mandrill-templates). The keys in the dict are the recipient email addresses, and the values are dicts of merge vars for each recipient:

message.merge_vars = {
    'wiley@example.com': {'offer': "15% off anvils"},
    'rr@example.com':    {'offer': "instant tunnel paint"}
}

Merge data must be strings or other JSON-serializable types. (See formatting-merge-data for details.)

tags

list of str: tags to apply to the message, for filtering reports in the Mandrill dashboard. (Note that Mandrill prohibits tags longer than 50 characters or starting with underscores.) :

message.tags = ["Order Confirmation", "Test Variant A"]

subaccount

str: the ID of one of your subaccounts to use for sending this message. (The subaccount on an individual message will override any global MANDRILL_SUBACCOUNT setting.)

0.7

google_analytics_domains

list of str: domain names for links where Mandrill should add Google Analytics tracking parameters. :

message.google_analytics_domains = ["example.com"]

google_analytics_campaign

str or list of str: the utm_campaign tracking parameter to attach to links when adding Google Analytics tracking. (Mandrill defaults to the message's from_email as the campaign name.)

metadata

dict: metadata values Mandrill should store with the message for later search and retrieval. :

message.metadata = {'customer': customer.id, 'order': order.reference_number}

Mandrill restricts metadata keys to alphanumeric characters and underscore, and metadata values to numbers, strings, boolean values, and None (null).

recipient_metadata

dict: per-recipient metadata values. Keys are the recipient email addresses, and values are dicts of metadata for each recipient (similar to merge_vars)

Mandrill restricts metadata keys to alphanumeric characters and underscore, and metadata values to numbers, strings, boolean values, and None (null).

async

Boolean: whether Mandrill should use an async mode optimized for bulk sending.

0.7

ip_pool

str: name of one of your Mandrill dedicated IP pools to use for sending this message.

0.7

send_at

datetime or date or str: instructs Mandrill to delay sending this message until the specified time. (Djrill allows timezone-aware Python datetimes, and converts them to UTC for Mandrill. Timezone-naive datetimes are assumed to be UTC.)

0.7

These Mandrill-specific properties work with any ~django.core.mail.EmailMessage-derived object, so you can use them with many other apps that add Django mail functionality.

If you have questions about the python syntax for any of these properties, see DjrillMandrillFeatureTests in tests/test_mandrill_send.py for examples.

Mandrill Response

A mandrill_response property is added to each ~django.core.mail.EmailMessage that you send. This allows you to retrieve message ids, initial status information and more.

For an EmailMessage that is successfully sent to one or more email addresses, mandrill_response will be set to a list of dict, where each entry has info for one email address. See the Mandrill docs for the messages/send API for full details.

For example, to get the Mandrill message id for a sent email you might do this:

msg = EmailMultiAlternatives(subject="subject", body="body",
                             from_email="sender@example.com",to=["someone@example.com"])
msg.send()
response = msg.mandrill_response[0]
mandrill_id = response['_id']

For this example, msg.mandrill_response might look like this:

msg.mandrill_response = [
    {
        "email": "someone@example.com",
        "status": "sent",
        "_id": "abc123abc123abc123abc123abc123"
    }
]

If an error is returned by Mandrill while sending the message then mandrill_response will be set to None.

0.8 mandrill_response available for sent messages

Exceptions

0.3 Djrill-specific exceptions

djrill.NotSupportedByMandrillError

If the email tries to use features that aren't supported by Mandrill, the send call will raise a ~!djrill.NotSupportedByMandrillError exception (a subclass of ValueError).

djrill.MandrillAPIError

If the Mandrill API fails or returns an error response, the send call will raise a ~!djrill.MandrillAPIError exception (a subclass of requests.HTTPError). The exception's status_code and response attributes may help explain what went wrong. (Tip: you can also check Mandrill's API error log to view the full API request and error response.)