我成功地使用 django/python 设置了一个 webhook 来解析传入的 SendGrid 电子邮件。但是,我收到一个错误,无法解析我收到的数据。错误表明我收到的身体是空的,事实并非如此。
@csrf_exempt
def receive_email_hook(request):
print("request.body: ",request.body)
try:
data = json.loads(request.body.decode('utf-8'))
sender = data['from']
recipient = data['to']
subject = data['subject']
body = data['html']
print("SUBJECT: "+str(subject))
return HttpResponse(status=200)
except Exception as e:
print("ERROR: "+str(e))
return HttpResponse(status=400)
我的错误是:
ERROR: Expecting value: line 1 column 1 (char 0)
当我打印 request.body 时,我得到:
request.body: b'--xYzZY\r\nContent-Disposition: form-data; name="headers"\r\n\r\nReceived: (...)
完整版包含电子邮件中的所有信息和我期望的所有数据。似乎只是解析错误,但无法弄清楚。我问了 Chat GPT,但得到了一些糟糕的答案,所以人类同胞,你能帮忙吗?
解决了:
@csrf_exempt
def receive_email_hook(request):
envelope = json.loads(request.POST.get('envelope'))
to_address = envelope['to'][0]
from_address = envelope['from']
# Now, onto the body
subject = request.POST.get('subject')
text = request.POST.get('text')
从 SendGrid 的 Flask 示例转换而来:https://docs.sendgrid.com/for-developers/tracking-events/python-code-example