为了账号安全,请及时绑定邮箱和手机立即绑定

在 AWS SES 中使用 Python 对退回的电子邮件进行 Json 解析

在 AWS SES 中使用 Python 对退回的电子邮件进行 Json 解析

慕码人2483693 2021-06-09 22:54:30
我正在尝试为 AWS SNS 编写一个 lambda 函数来捕获退回的电子邮件。我可以成功捕捉到通知类型“Delivery”的详细信息,但不能捕捉到“bounce”类型的详细信息。python 中的一些语法问题,我不知道 python 但在 SES 中没有其他选项。我的代码如下。def lambda_handler(event, context):message = event.get("Records")[0].get("Sns").get("Message")parsed_message = json.loads(message)status = parsed_message.get("notificationType")event_date = parsed_message.get("mail").get("timestamp")recipients = []if (status == "Bounce"):    for r in parsed_message.get("bounce").get("bouncedRecipients"):        parsed_r = json.loads(r)        recipients.append(parsed_r[0].get("emailAddress"))elif (status == "Complaint"):    for r in parsed_message.get("complaint").get("complainedRecipients"):        recipients.append(r)elif (status == "Delivery"):    for r in parsed_message.get("delivery").get("recipients"):        recipients.append(r)conn = make_conn()cur = conn.cursor()cur.execute("insert into email_event (email_status, event_date, email_address, event_json) values (%s, %s, %s, %s)", (status, event_date, ";".join(recipients), json.dumps(event)))conn.commit()cur.close()conn.close()parsed_message 的 Json 如下 {   "notificationType": "Bounce",   "bounce": {      "bounceType": "Permanent",      "bounceSubType": "Suppressed",      "bouncedRecipients": [         {            "emailAddress": "email@email.com",            "action": "failed",            "status": "5.1.1",            "diagnosticCode": "Amazon SES has suppressed sending to this address because it has a recent history of bouncing as an invalid address. "         }      ],   },我收到这样的错误 JSON 对象必须是 str、bytes 或 bytearray,而不是 'dict': TypeError我试过如下for r in parsed_message.get("bounce").get("bouncedRecipients")[0].get("emailAddress")recipients.append(r)但这在数据库中保存为 e;m;a;i;l;@;e;m;a;i;l;.;c;o;m
查看完整描述

1 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

“bouncedRecipients”指向一个字典列表,每个被退回的收件人一个。

要遍历该列表,然后获取电子邮件地址应如下所示:

for r in parsed_message.get("bounce").get("bouncedRecipients"):
    recipients.append(r.get("emailAddress"))

或者,不像 Java 而更像 Python:

for r in parsed_message["bounce"]["bouncedRecipients"]:
    recipients.append(r["emailAddress"])

这也可以写成列表理解为:

recipients = [r["emailAddress"] for r in parsed_message["bounce"]["bouncedRecipients"]]


查看完整回答
反对 回复 2021-06-15
  • 1 回答
  • 0 关注
  • 148 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号