Django SendGrid 如何在 EmailMultiAlternatives 邮件对象中传递 unique_args

Sha*_*riq 2 django django-email sendgrid

SendGrid 提供了将unique_args与电子邮件一起传递的功能,以便在事件 webhook 中识别电子邮件 但问题是我无法弄清楚如何在 Django 中通过电子邮件发送这些 un​​ique_args。这就是我目前尝试这样做的方式:

from django.core.mail import EmailMultiAlternatives

header ={
  "unique_args": {
    "customerAccountNumber": "55555",
    "activationAttempt": "1",
    "New Argument 1": "New Value 1",
    "New Argument 2": "New Value 2",
    "New Argument 3": "New Value 3",
    "New Argument 4": "New Value 4"
  }
}

subject, from_email, to = 'hello', 'EXAMPLE@FROM.com', 'EXAMPLE@TO.NET'
text_content = 'This is an important message.'
msg = EmailMultiAlternatives(
subject,
text_content,
from_email,
[to,],
headers=header,
)
msg.send()
Run Code Online (Sandbox Code Playgroud)

Sha*_*riq 6

好的,所以最后我找到了解决方案。最后,我想出了如何使用 Django EmailMultiAlternatives 将 unique_args 发送到 SendGrid。这是我的工作解决方案:

    from django.core.mail import EmailMultiAlternatives
    from smtpapi import SMTPAPIHeader
    header = SMTPAPIHeader()
    header.set_unique_args({'customerAccountNumber': '12345','activationAttempt': '1'})

    subject, from_email, to = 'hello', 'EXAMPLE@FROM.com', 'EXAMPLE@TO.NET'
    text_content = 'This is an important message.'
    msg = EmailMultiAlternatives(
        subject,
        text_content,
        from_email,
        [to,],
        headers={'X-SMTPAPI': header.json_string()},
    )
    msg.send()
Run Code Online (Sandbox Code Playgroud)

您还需要通过以下方式安装 smtpapi 包 pip install smtpapi