如何将 Mailgun 收件人变量与 Django SMTP 电子邮件后端一起使用?

How to use Mailgun's recipient-variables with Django SMTP mail backend?

如何在使用 SMTP 协议的 Django 中使用 MailGun 正确发送 batch/bulk/mass emails

到目前为止我尝试了什么?

这是我尝试发送电子邮件的代码片段。

from django.core.mail import EmailMultiAlternatives
import json

to_emails = [
    "mail_1@example.com",
    "mail_2@example.com",
    "mail_3@example.com",
    "mail_4@example.com",
    "jerinpetergeorge@gmail.com",
]
mail = EmailMultiAlternatives(
    subject="Hey - %recipient.name%",
    body="Hey %recipient.name%,\n\nThis is just a batch email test!!!",
    from_email="JPG <me@somehost.com>",
    to=to_emails,
)
recipient_variables = {
    address: {"name": address} for address in to_emails
}
mail.extra_headers["X-Mailgun-Recipient-Variables"] = json.dumps(recipient_variables)
response = mail.send()
print(response)

我收到了如下邮件,

我们可以看到,to属性填充了所有的邮箱地址,这不是我所期待的.

那么,如何让 Mailgun/Django 正确解析我的变量以使电子邮件看起来更个性化?


备注


更新 1

As we can see, the to attribute is filled with all email addresses, which is not what I am expecting.

Mailgun 不正确支持 SMTP。

但是,依靠 Mailgun 中 BCC 的(不直观的)实现,有一个解决方法:

mail = EmailMultiAlternatives(
    subject="Hey - %recipient.name%",
    body="Hey %recipient.name%,\n\nThis is just a batch email test!!!",
    from_email="JPG <me@somehost.com>",
    # to=to_emails,  # Replace this
    bcc=to_emails,   # with this
)
recipient_variables = {
    address: {"name": address} for address in to_emails
}
mail.extra_headers["To"] = "%recipient%"  # Add this
mail.extra_headers["X-Mailgun-Recipient-Variables"] = json.dumps(recipient_variables)

参考:


  1. 为什么 to=["%recipient%"] 不能使用 SMTP?

这是协议中的标准。

来自 https://documentation.mailgun.com/_/downloads/en/latest/pdf/:

SMTP send will error with “cannot parse to address” or “cannot parse from address” if the provided email address fails syntax checks in accordance with RFC5321, RFC5322, RFC6854.

  1. 如何正确支持使用 Mailgun 批量发送?

使用API.

来自 (multiposted to https://laracasts.com/discuss/channels/laravel/sending-email-to-1000s-of-reciepents):

So far, I have created an array of recipient email addresses, sent the email to a webmaster type address, and included the end recipients in BCC

While this works, it's not ideal.

Rather than using Laravel's built in Mail, I elected to use Mailgun's API (specifically batch sending) directly

This also allows me to access unique recipient variables within my email template

(不特定于 Laravel/PHP,而是通过 Mailgun 特定于 SMTP。)

  1. Mailgun 中 BCC 的“不直观”实现是什么意思?

Mailgun 使用收件人变量为每个 BCC 收件人有效地个性化电子邮件。

来自 https://github.com/mailgun/mailgun-js-boland/issues/89:

the bcc person is receiving the email as it was addressed to them instead of being part of the bcc

当您实际上希望 BCC 收件人获得相同的内容时,这会导致一个单独的问题。

来自 :

In the copy sent to the bcc address, the recip_vars substitution has not been made.

According to the good people at Mailgun, this is not possible, at least in the current release of the service.