首页 > 解决方案 > SendGrid Django 模板标签返回 HTTP 错误 400:错误请求

问题描述

有一个烦人的问题。我正在使用 Django 将数据发送到 sendGrid 模板。但是当我添加替换时,我得到一个 HTTP 错误 400:错误请求。如果我不在字典中添加任何内容,它可以按预期通过电子邮件发送模板。所以我确定问题出在标签格式上,我似乎找不到正确的组合

Python

    def emailSendGrid(self):
    mail = EmailMultiAlternatives(
        subject="Your Subject from sendGrid",
        body="SendGrid sent This is a simple text email body.",
        from_email="anon@test",
        to=["dude@test"],
        headers={"Reply-To": "anon@test"}
    )
    # Add template
    mail.template_id = '#######################'

    # Replace substitutions in sendgrid template
    mail.substitutions = {'testTag': 'new content from Django'}


    fail_silently = False
    mail.send()

发送网格模板

    <html>
<head>
  <title></title>
</head>
<body>
  <h3>This is a test email template from sendGrid</h3>
  <p> -testTag- </p>
</body>
</html>

这应该很简单,但我已经尝试过,所以我的组合并没有解决。

标签: djangopython-3.xsendgrid

解决方案


我最终使用了 Django 的 curl 帖子。希望这对将来的某人有所帮助。我还为 python、php、R 和 node.js 转换器找到了一个非常好的 curl 代码,它也有很大帮助。https://curl.trillworks.com/

import requests

headers = {
        'authorization': 'Bearer API_KEY',
        'Content-Type': 'application/json',
    }
    testData = 'This is new testing data'
    data = '{"personalizations": [{"to": [{"email": "to_email_Address"}], "dynamic_template_data": {"testTag": "My new data"}}],"from": {"email": "from_email"},"subject":"Hello, World!","content": [{"type": "text/plain","value": "Heya!"}] ,"template_id" : "TEMPLAT_ID"}'

特别感谢 dirkgroten 为我指明了正确的方向。 https://stackoverflow.com/users/1252711/dirkgroten


推荐阅读