通过AWS Lambda函数发送电子邮件

时间:2019-11-12 01:38:37

标签: amazon-web-services aws-lambda amazon-ses

我已经创建了一个基本的lambda函数,该函数应该从SES服务发送电子邮件,但无法正常工作。

我已经遵循了本教程:here。我已经创建了正确的IAM策略并将其附加到功能上,但是我认为这不是问题所在。

我已经使用创建了该功能的测试配置,并且控制流没有到达sendEmail内部,我不确定为什么。

const aws = require('aws-sdk')
const ses = new aws.SES({ region: 'us-east-1' });

exports.handler = async (event, context, callback) => {
  const printOut = JSON.stringify(event);
  console.log(`Received event: ${printOut}`);

  const params = {
    Destination: {
      ToAddresses: ["xxxxx.xxxx@gmail.com"]
    },
    Message: {
      Body: {
        Text: {
          Data: event['desc']
        }
      },
      Subject: {
        Data: "Email from xxxxxxx Contact Us Form"
      }
    },
    Source: "xxxxxxxxxxxxxxxxx@gmail.com"
  };

  console.log(`sending: ${JSON.stringify(params)}`);

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

    console.log(`Done!`);
  });
};

这是我当前的输出:

Response:
null

Request ID:
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxx"

Function Logs:
START RequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxx Version: $LATEST
2019-11-12T01:28:48.352Z    xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxx  INFO    Received event: {"name":"Redacted","email":"xxxxx.xxxx@gmail.com","desc":"Test message"}
2019-11-12T01:28:48.372Z    xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxx  INFO    sending: {"Destination":{"ToAddresses":["xxxxx.xxxx@gmail.com"]},"Message":{"Body":{"Text":{"Data":"Test message"}},"Subject":{"Data":"Email from xxxxxx Contact Us Form"}},"Source":"xxxxxxxxxxxxxxx@gmail.com"}
END RequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxx
REPORT RequestId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxx    Duration: 590.10 ms Billed Duration: 600 ms Memory Size: 128 MB Max Memory Used: 94 MB  Init Duration: 359.55 ms    

如您所见,sendEmail函数内部的控制台中断/错误永远不会被调用。不太确定为什么。

我确实确保验证正在测试的两个电子邮件地址,但没有骰子。

1 个答案:

答案 0 :(得分:2)

您必须使其非异步或将promise返回给调用方(您可以将该promise直接返回给运行时)。像这样:

const aws = require('aws-sdk')
const ses = new aws.SES({region: 'us-east-1'});

exports.handler = async (event, context, callback) => {
    const printOut = JSON.stringify(event);
    console.log(`Received event: ${printOut}`);

    const params = {
        Destination: {
            ToAddresses: ["xxxxx.xxxx@gmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: event['desc']
                }
            },
            Subject: {
                Data: "Email from xxxxxxx Contact Us Form"
            }
        },
        Source: "xxxxxxxxxxxxxxxxx@gmail.com"
    };

    console.log(`sending: ${JSON.stringify(params)}`);

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