1

I want to send emails using the ses from aws from lambda. The problem is that the email is only sent some times using the same code. We don't get errors.

Here's the code:

const AWS = require('aws-sdk');
var ses = new AWS.SES();

exports.handler = async (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;

    await new Promise((resolve, reject) => {

      var params = {
        Destination: {
            ToAddresses: [myEmail]
        },
        Message: {
            Body: {
                Text: { Data: "Test"

                }

            },

            Subject: { Data: "Test Email"

            }
        },
        Source: "sourceMail"
    };

    ses.sendEmail(params, function (err, data) {

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

    });
}
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
vDrews
  • 155
  • 5
  • 14

1 Answers1

6

I would be careful with using callbackWaitsForEmptyEventLoop as it can lead to unexpected results (If this is false, any outstanding events continue to run during the next invocation.).

Can you try using this simplified version:

const AWS = require('aws-sdk');
var ses = new AWS.SES();

exports.handler = async (event, context, callback) => {
  const params = {
    Destination: {
      ToAddresses: [myEmail],
    },
    Message: {
      Body: {
        Text: { Data: 'Test' },
      },

      Subject: { Data: 'Test Email' },
    },
    Source: 'sourceMail',
  };

  await ses.sendEmail(params).promise();

  return event;
};
Erez
  • 1,690
  • 8
  • 9