Lambda Function refuses to run callback inside nodemailer transporter functions and wait for results from function

I have a lambda function sending email from a contact form using nodemailer. The problem is I have that the lambda function refuses to let me put the call back function inside the transporter.send mail function like in this example.(https://github.com/kicholen/makeithappen/blob/79b9c8f3a7238dc75308f9a69d769d7cda7dd522/func/sendMail.js)`

  transporter.sendMail({
    from: process.env.MAIL_LOGIN,
    to: process.env.MAIL_TO,
    subject: process.env.SUBJECT + new Date().toLocaleString(),
    text: event.body
}, function(error, info) {
	if (error) {
		callback(error);
	} else {
		callback(null, {
			    statusCode: 200,
			    body: "Ok"
	    	});
	}
  });

But when I tried to do the same the lambda function continues to run indefinitely even after an email was sent. I want to have the callback function inside the send mail function like in the example so I can send an info or error message back to the client side. Right now I have the callback function outside of the transporter.sendmail function, but now the callback function is being executed quicker than the transporter.sendmail function can be executed.

transporter.sendMail(mailoptions, function (error, info) {
    if (error) {  
    } else {
      console.log(`Message sent`, info.messageId)
    }
  })

  return callback(null, {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers": "Content-Type",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",
    },
    body: `{"message": "lambda function executed"}`,
  })

Is there something I’m doing wrong when it comes to setting up the lambda?

Hello @grantmontgomery,

Since sendMail returns a promise, have you tried making your lambda function an async one? And then make sure you ‘await’ your sendMail call. Let me know if that helps.

Yup switched it to async a few days ago and it works now thanks Dennis!

1 Like