我正在开发一个基于GAE(Google App Engine)的python应用程序,并且其中集成了sendgrid python SDK(v3.2.10)。我现在想做的是,每当sendgrid推送类型为“ bounce”的事件webhook时,我都希望从sendgrid上存在的退回电子邮件列表中删除该退回电子邮件。
我已经阅读了官方网站上提供的文档。首先,我尝试使用SDK删除电子邮件地址,该地址在localhost上运行良好。但是,将其部署到实时服务器后,它什么也不做,就进入了异常子句。
代码段:
try:
send_grid_client = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
data = {"emails": [email.strip()]}
delete_response = send_grid_client.client.suppression.bounces.delete(
request_body=data)
except Exception as exception:
logging.info('Exception is: {}'.format(exception))
pass
由于它没有按预期工作,因此我现在尝试使用REST API进行相同的操作。
代码段:
import requests
data = {"emails": [email]}
headers = {"Authorization": "Bearer {}".format(SENDGRID_API_KEY)}
delete_response = requests.delete("https://api.sendgrid.com/v3/suppression/bounces", data=json.dumps(data), headers=headers)
logging.info(delete_response)
logging.info(delete_response.status_code)
logging.info(delete_response.text)
现在,sendgrid API不断返回错误400和消息{"errors":[{"field":null,"message":"emails or delete_all params required"}]}
。我根本不知道如何克服这个问题。也许我错过了如何在delete
函数中传递请求正文,但是我无法弄清楚。
答案 0 :(得分:0)
我刚发现问题。
SendGrid API文档here引起混乱,因为当您要删除单个电子邮件地址或电子邮件列表时,并未明确提及它们具有不同的调用同一终结点的方式。
对于一封电子邮件,需要在URL中传递,即https://api.sendgrid.com/v3/suppression/bounces/{email_address}
对于电子邮件列表,该列表需要在删除请求的正文中传递。即看起来像这样{"emails": [email_address_1, email_address_1, ...]}
与上面的问题一样,本来应该删除一封电子邮件,并且在删除请求中将其作为{"emails": [email_address_1]}
传递。 Sendgrid API无法提取此信息,并引发错误。该电子邮件地址将在URL中传递。
此问题已解决。但是,我想知道为什么Sendgrid API无法提取此信息{"emails": [email_address_1]}
。为什么他们有一个艰难的假设,即列表中的元素总是大于一个。