3

It's been a while since I last programmed and I have a simple problem. I don't know how to respond to a request once I sent an email using AWS Lambda & API Gateway (not REST but HTTP API).

I have a form that sends basic contact details to a Lambda function. It generates an email successfully. I now want to respond to the form informing it was successful. My Lambda code below, all examples I can find simply return the promise or just log the outcome in the Lambda function. If I return the promise I get a server 500 error.

I want to respond with all ok if successful or an error if there was a problem. Many thanks.

const aws = require("aws-sdk");
const ses = new aws.SES();
exports.handler = async function (event, context, callback) {
  console.log('EVENT: ', event)
  
  const { name, email, phone, message } = JSON.parse(event.body)
  
  const params = {
    Destination: {
      ToAddresses: ["RECIEVER EMAIL I SUBBED IN REAL CODE"],
    },
    Message: {
      Body: {
        Text: { 
            Data: `Hello from Lambda! You got a message from ${name}. \n Contact Details: \n - Email: ${email} \n - Phone: ${phone} \n ${message}` 
        },
      },
      Subject: { Data: `Enquiry from ${name}` },
    },
    Source: "SENDER EMAIL I SUBBED IN REAL CODE",
  };

  return ses.sendEmail(params).promise()
};

1 Answer 1

1

It's returning 500 because the resolved promise from ses.sendEmail() doesn't match the required type for the handler. You must return HTTP-Response as required by ApiGateway.

exports.handler = async function(event, context) { // you don't need callback on async
  /* your code */
  try {
    await see.sendEmail(params).promise();
    return {
      statusCode: 200,
    };
  } catch (e) {
    return {
      statusCode: 500,
      body: "a message that helps you",
    };
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.