如何使用最新版本的 Node 通过 aws-sdk v3 在 Lambda 中发送 AWS SES 电子邮件?

问题描述 投票:0回答:1

如何使用 NodeJS 20 在 AWS Lambda 中验证 Google Recaptcha,然后在使用 AWS SES 成功时发送电子邮件?假设面向前端的表单通过变量

gRecapResp
发送 Recaptcha 响应。我发现的很多答案都使用 Node 16 或更早版本,这不适用于最新版本的 Node。我不想使用任何打包的 zips 层。

node.js amazon-web-services rest aws-lambda amazon-ses
1个回答
0
投票

我无法在 AWS Lambda 上找到用于 HTML Recaptcha 验证的 Node 20 的最新答案,因此我自己设计了一个。您不需要添加任何包或层,但您必须更改一些事件变量并添加 Recaptcha 密钥。我将其与 API 网关连接起来。如果 recpatcha 验证成功 (MailSent),它会使用 SES 发送电子邮件。

gRecapResp
是用户在前端表单上输入的响应。它通过 API 网关通过 REST 发送到 Lambda 函数。您还需要更改下面列出的两个电子邮件地址。所有事件变量都需要像
event.name
一样进行更改以满足您的需求。如果您在此过程中遇到问题,请使用
console.log
或在下面添加评论。

'use strict';
import { HttpRequest } from "@aws-sdk/protocol-http";
import { SESClient, SendEmailCommand } from "@aws-sdk/client-ses";
import { NodeHttpHandler } from "@aws-sdk/node-http-handler";
export const reCaptchaSecret = "ADDSECRET";
const REGION = "us-east-1";
const sesClient = new SESClient({ region: REGION });
export { sesClient };

export const handler = async (event, context, callback) => {
  // Grab the following variable from the User facing form.
  console.log(event.gRecapResp);
  const apiUrl = new URL('https://www.google.com/recaptcha/api/siteverify?secret=' + reCaptchaSecret + '&response=' + event.gRecapResp);
  const request = new HttpRequest({
    hostname: apiUrl.hostname.toString(),
    protocol: apiUrl.protocol,
    path: apiUrl.pathname +  apiUrl.search.toString(),
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "host": apiUrl.hostname.toString(),
    },
  });
  const client = new NodeHttpHandler();
  const { response } = await client.handle(new HttpRequest(request));
  console.log(response.statusCode + ' ' + response.body.statusMessage);
  var responseBody = '';
  await new Promise(() => {
    response.body.on('data', (chunk) => {
      responseBody += chunk;
    });
    response.body.on('end', () => {
      console.log('responseBody' + JSON.parse(responseBody).success);
      if (JSON.parse(responseBody).success) {
        const command = new SendEmailCommand({
          Destination: {
            ToAddresses: [
              '[email protected]'
            ]
          },
          Message: {
            Body: {
              Text: {
                Data: 'Name: ' + event.name + '\n\nEmail: ' + event.mail + '\n\nMessage: ' + event.message,
                Charset: 'UTF-8'
              }
            },
            Subject: {
              Data: event.referrer + ' Website Referral: ' + event.name,
              Charset: 'UTF-8'
            }
          },
          Source: '[email protected]'
        });
        try {
          return sesClient.send(command);
        }
        catch (error) {
          callback('MailNotSent');
        }
        finally {
          callback(null, 'MailSent');
        }
      } else {
        callback('MailNotSent');
      }
    });
  }).catch((error) => {
    callback('MailNotSent');
  });

};
© www.soinside.com 2019 - 2024. All rights reserved.