Json 在 AWS SES 中解析 python 中的退回邮件

Json Parsing for bounced emails in python in AWS SES

我正在尝试为 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()

Json 对于 parsed_message 低于

 {
   "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

"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"]]