Search code examples
amazon-web-servicesaws-lambdaboto3aws-step-functions

AWS StepFunction : Getting Error as "error": "KeyError"


I am new to AWS and Step functions. I am trying to run simple program from Step function using Lambda function. I have tried below code to run the Step function.

code:

import boto3
import json
import os



def lambda_handler(event, context):


    subject = event['Mail']['subject']
    toList = event['Mail']['mailTo'] 
    message = event['MailMessage']['message']
    status = ""


    body = message 

    subject="["+status+"]"+subject


    for to in toList.split(","):
        sendMail(to, ADMIN_EMAIL, subject, body)

    return event


def sendMail(to, reply, subject, body):
    client = boto3.client('ses', region_name=region_name)
    response = client.send_email(
        Source=reply,
        Destination={
            'ToAddresses': [
                to,
            ]
        },
        Message={
            'Subject': {
                'Data': subject,
            },
            'Body': {
                'Text': {
                    'Data': body,
                },
            }
        },
        ReplyToAddresses=[
            reply,
        ],
        ReturnPath=reply
    )
    return response

after running the Step function, I am getting below error.

{
  "error": "KeyError",
  "cause": {
    "errorMessage": "'Mail'",
    "errorType": "KeyError",
    "stackTrace": [
      [
        "/var/task/lambda_function.py",
        11,
        "lambda_handler",
        "subject = event['Mail']['subject']"
      ]
    ]
  }
}

My step function :

{
  "Comment": "A Sample program to send an email",
  "StartAt": "SampleMail",
  "States": {
    "SampleMail": {
      "Type": "Task",
     "Resource": "arn:aws:lambda:us-west-1:000000123:function:TestEmail", 

      "End": true
    }
  }
}

could you please tell me what i am missing here?

Kindly help me.

Many thanks for your help.


Solution

  • The event passed to your lambda_handler function does not have a key called "Mail", so this line

    subject = event['Mail']['subject']
    

    is failing. You should verify the event parameter has a 'Mail' attribute before retrieving any values with that key.