提问者:小点点

如何在Django SMTP邮件后端使用Mailagle的收件人变量?


如何使用SMTP协议在Django中使用MailGun正确发送批/批量/批量电子邮件?

  • 我使用django.core.mail.backends.smtp.Email Backend作为我的EMAIL_BACKEND

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

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正确解析我的变量以使电子邮件看起来更个人化呢?

笔记

  • 我更喜欢用SMTP协议
  • 我已经尝试了Mailgen的REST API,它是成功的(但是,我更喜欢SMTP)
  • 我找到了django-anymail,似乎它有这个功能。但是,它也使用API(如果我错了,请纠正我)

>

>


共1个答案

匿名用户

正如我们所看到的,to属性填充了所有的电子邮件地址,这不是我所期望的。

它不受Mailgun SMTP的正确支持。

然而,依赖于Mailagle中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)

参考:https://stackoverflow.com/questions/37948729/mailgun-smtp-batch-sending-with-recipient-variables-shows-all-recipients-in-to-field

  1. 为什么to=[%recipient%]不适用于SMTP

这是协议中的标准。

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

如果提供的电子邮件地址未能按照RFC5321、RFC5322、RFC6854进行语法检查,SMTP发送将出现“无法解析到地址”或“无法从地址解析”的错误。

使用API。

从…起https://stackoverflow.com/questions/30787399/laravel-5-sending-group-emails(多端口到)https://laracasts.com/discuss/channels/laravel/sending-email-to-1000s-of-reciepents):

到目前为止,我已经创建了一系列收件人电子邮件地址,将电子邮件发送到网站管理员类型的地址,并将最终收件人包括在密件抄送中

虽然这很有效,但并不理想。

我没有使用Laravel内置的Mail,而是选择直接使用Mailagle的API(特别是批量发送)

这还允许我访问电子邮件模板中唯一的收件人变量

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

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

从…起https://github.com/mailgun/mailgun-js-boland/issues/89:

密件抄送人收到的是发送给他们的电子邮件,而不是密件抄送人的一部分

当您实际希望密件抄送收件人获得相同的内容时,这会导致另一个问题。

从https://stackoverflow.com/questions/48887866/bcc-in-mailgun-batch-send-does-not-include-substitutions:

在发送至密件抄送地址的副本中,未进行副本替换。

据Mailgun的好人说,这是不可能的,至少在目前的服务版本中是不可能的。

相关问题