djangoemailhtml-emailmandrillbulk-email

How to get mandrill response for every message when sending html bulk emails with djrill?


I'm about to integrate into a project some bulk email features using mandrill and djrill 1.3.0 with django 1.7, since I'm sending html content I'm using the following approach:

from django.core.mail import get_connection

connection = get_connection()
to = ['testaddress1@example.com', 'testaddress1@example.com'] 
for recipient_email in to:
    # I perform some controls and register some info about the user and email address
    subject = u"Test subject for %s" % recipient_email
    text = u"Test text for email body"
    html = u"<p>Test text for email body</p>"
    from_email = settings.DEFAULT_FROM_EMAIL
    msg = EmailMultiAlternatives(
        subject, text, from_email, [recipient_email])
    msg.attach_alternative(html, 'text/html')
    messages.append(msg)
# Bulk send
send_result = connection.send_messages(messages)

At this point, send_result is a int and it equals to the number of sent (pushed to mandrill) messages.

I need to get the mandrill response for every sent message to process the mandrill_response['msg']['_id'] value and some other stuff.

djrill provided 'send_messages' connection method uses a _send call and it is adding mandrill_response to every message but is just returning True if success.

So, do you know how to get mandrill response for every message when sending bulk html emails with djrill?


Solution

  • Djrill attaches a mandrill_response attribute to each EmailMessage object as it's sent. See Mandrill response in the Djrill docs.

    So after you send the messages, you can examine that property on each object in the messages list you sent. Something like:

    # Bulk send
    send_result = connection.send_messages(messages)
    
    for msg in messages:
       if msg.mandrill_response is None:
           print "error sending to %r" % msg.to
       else:
           # there's one response for each recipient of the msg
           # (because an individual message can have multiple to=[..., ...])
           for response in msg.mandrill_response:
               print "Message _id %s, to %s, status %s" % (
                   response['_id'], response['email'], response['status'])
    
    >>> Message _id abc123abc123abc123abc123abc123, to testaddress1@example.com, status sent
    >>> ...