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

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


慕码人2483693
浏览 149回答 1
1回答

陪伴而非守候

“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"]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python