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

时间:2015-05-06 08:33:35

标签: django email html-email mandrill bulk-email

我即将使用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是一个int,它等于发送(推送到mandrill)消息的数量。

我需要为每封已发送的邮件获取mandrill响应,以处理mandrill_response [&#39; msg&#39;] [&#39; _id&#39;]值和其他一些内容。

djrill提供了&#39; send_messages&#39; connection方法使用_send调用,它正在向每条消息添加mandrill_response,但如果成功则返回True。

那么,您是否知道在使用djrill发送批量HTML电子邮件时如何获取每条消息的mandrill响应?

1 个答案:

答案 0 :(得分:0)

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