2

I am trying to create an AWS Lambda trigger that sends email to a user. The Lambda is triggered by SQS, where I will be pushing my messages from my code. Now when I am using test cases on Lambda, everything is working fine, but when I am sending json data over SQS (which is sent to by using python), all the fields are shown as undefined. Following is my Lambda code:

var aws = require('aws-sdk');
var ses = new aws.SES({region: 'ap-south-1'});

var RECEIVER = '[email protected]';
var SENDER = '[email protected]';

var response = {
 "isBase64Encoded": false,
 "headers": { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'},
 "statusCode": 200,
 "body": "{\"result\": \"Success.\"}"
 };
 

exports.handler = (event, context, callback) => {
    
 var params = {
    Destination: {
        ToAddresses: [
                RECEIVER
            ]
    },
    Message: {
        Body: {
            Text: {
                Data: 'My Name is ' + event.user +'\nTimestamp:'+ event.timestamp,
                Charset: 'UTF-8'
            }
        },
        Subject: {
            Data: 'Test : ' + event.name,
            Charset: 'UTF-8'
        }
    },
    Source: SENDER
};


 ses.sendEmail(params, function (err, data) {
    callback(null, {err: err, data: data});
    if (err) {
        console.log(err);
        context.fail(err);
    } else {
        
        console.log(data);
        context.succeed(event);
    }
});
};

My Python File:

class SQSQueue(object):
    def __init__(self, queueName=None):
        self.resource = boto3.resource('sqs',region_name="xxxxxxx")
        self.queue = self.resource.get_queue_by_name(QueueName=AWS_SQS_QUEUE_NAME)
        self.QueueName = queueName
    
    def send(self, Message={}):
        data = json.dumps(Message)
        response = self.queue.send_message(MessageBody=data)
        return response
    
    
if __name__ == '__main__':
    q = SQSQueue(queueName=AWS_SQS_QUEUE_NAME)
    name = "xxxxxxx"
    timestamp = "yyyyyyyy"
    message = {
        "user": name,
        "timestamp": timestamp
    }
    
    response = q.send(Message=message)

I am not a node developer, and have no knowledge of the language, I just followed a couple of posts/videos and developed this.

Posts I referred for this query: AWS Lambda Javascript JSON object undefined AWS Lambda with API Gateway throwing response error

Output I am getting on my email:

My Name is undefined
Timestamp:undefined
1
  • Can you console log the event object? Commented Sep 4, 2020 at 5:41

2 Answers 2

2

Payload of the sqs in not directly your message, it wraps also other details.

You have an array of records, so to get payload of your message try

event.Records.map(record => {
  const message = JSON.parse(record.body);
  // message.name , message.timestamp  ....
  processMessage(message);
});

It could be setup how many records to be received by the lambda using batch size https://docs.aws.amazon.com/lambda/latest/dg/API_CreateEventSourceMapping.html (BatchSize)

Sign up to request clarification or add additional context in comments.

Comments

1

I think something is not right with the processing of the your messages. The lambda will always process a list of records (which correspond to messages) instead of processing one message at a time.

You can check here what you cant expect on the event https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html

{
    "Records": [
        {
            "messageId": "059f36b4-87a3-44ab-83d2-661975830a7d",
            "receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...",
            "body": "Test message.",
            "attributes": {
                "ApproximateReceiveCount": "1",
                "SentTimestamp": "1545082649183",
                "SenderId": "AIDAIENQZJOLO23YVJ4VO",
                "ApproximateFirstReceiveTimestamp": "1545082649185"
            },
            "messageAttributes": {},
            "md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3",
            "eventSource": "aws:sqs",
            "eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:my-queue",
            "awsRegion": "us-east-2"
        },
        {
            "messageId": "2e1424d4-f796-459a-8184-9c92662be6da",
            "receiptHandle": "AQEBzWwaftRI0KuVm4tP+/7q1rGgNqicHq...",
            "body": "Test message.",
            "attributes": {
                "ApproximateReceiveCount": "1",
                "SentTimestamp": "1545082650636",
                "SenderId": "AIDAIENQZJOLO23YVJ4VO",
                "ApproximateFirstReceiveTimestamp": "1545082650649"
            },
            "messageAttributes": {},
            "md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3",
            "eventSource": "aws:sqs",
            "eventSourceARN": "arn:aws:sqs:us-east-2:123456789012:my-queue",
            "awsRegion": "us-east-2"
        }
    ]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.