简体   繁体   中英

How to fix sending emails with AWS SES and Lambda?

I'm setting up a simple NodeJS Lambda function on AWS to send emails.

The code below is working when I run it locally. I have received all the credentials from AWS, verified both sender and recipient emails and granted all permissions to SES for my Lamba

const aws = require("aws-sdk");
const config = require('../config')

aws.config.update({
  accessKeyId: config.mailUser,
  secretAccessKey: config.mailPassword,
  region:'us-east-1'
});

const ses = new aws.SES({apiVersion: '2010-12-01'});

const sendEmail = async (mailOptions) => {
  const {
    from,
    to,
    subject,
    html
  } = mailOptions
  console.log('foo')
  ses.sendEmail({
    Source: from,
    Destination: {
      ToAddresses: [to]
    },
    Message: {
      Subject: {
        Data: subject,
        Charset: 'UTF-8'
      },
      Body: {
        Html: {
          Data: html,
          Charset: 'UTF-8'
        }
      }
    }
  }, 
  (err, data) => {
    console.log('baz')
    if (err) {
      console.error(err);
    } else {
      console.log('Email sent:');
      console.log(data);
    }
  });
};
console.log('bar')
module.exports = { 
  sendEmail 
};

It seems that ses.sendEmail() never fires when the function is deployed - I get foo and bar in the CloudWatch logs but never baz . Again, everything is running smoothly if run locally.
What is it that I am missing?

https://www.reddit.com/r/aws/comments/bf2iss/lambda_function_not_able_to_send_email_using_ses/elb8vzr/

Here is a very good explanation - apparently you need to wrap your ses.sendMail call in a promise for it to work with AWS Lambda.

All credit goes to https://www.reddit.com/user/jsdfkljdsafdsu980p/ and https://www.reddit.com/user/Enoxice/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM