使用 djrill 发送 html 群发邮件时,如何获取每条消息的 mandrill 响应?

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

我即将使用 mandrill 和 djrill 1.3.0 以及 django 1.7 将一些批量电子邮件功能集成到一个项目中,因为我要发送 html 内容,所以我使用以下方法:

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)

此时,send_result 是一个整数,它等于发送(推送到 mandrill)消息的数量。

我需要为每条发送的消息获取 mandrill 响应以处理 mandrill_response['msg']['_id'] 值和一些其他内容。

djrill 提供 'send_messages' 连接方法使用 _send 调用,它正在向每条消息添加 mandrill_response,但如果成功则返回 True。

那么,您知道在使用 djrill 发送批量 html 电子邮件时如何让每条消息都得到 mandrill 回复吗?

Djrill 在发送每个 EmailMessage 对象时附加一个 mandrill_response 属性。请参阅 Djrill 文档中的 Mandrill response

因此,在您发送消息后,您可以检查 属性 您发送的 messages 列表中的每个对象。类似于:

# 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
>>> ...