0
0

メール送信LambdaをAmplifyで作成

Last updated at Posted at 2024-09-26

メール送信LambdaをAmplifyで作成

Amplify で構築した環境で、DynamoDB の特定のテーブルにレコードが追加された際、Amazon SES を利用してメールを送信するLambda Trigger を作成しました。

Lambda Triggerを作成する

a2e5ac8e-02b5-4c74-914f-6839ee7b5cc5.png

amplify add function を使ってLambda Trigger を作成します。Cloudformation のテンプレートで、対象のテーブルへの権限は自動生成されます。

"PolicyDocument": {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "dynamodb:DescribeStream",
                "dynamodb:GetRecords",
                "dynamodb:GetShardIterator",
                "dynamodb:ListStreams"
              ],
            "Resource": {
                "Fn::ImportValue": {
                  "Fn::Sub": "${×××GraphQLAPIIdOutput}:GetAtt:(テーブル名)Table:StreamArn"
                }
            }
        }
    ]
}

Amazon SES を使うためにポリシーを設定します。
cloudformation-template.json のlambdaexecutionpolicy/Properties/PolicyDocument/statement に以下を追加します。

{
    "Effect": "Allow",
    "Action": [
        "ses:SendEmail",
        "ses:SendRawEmail"
    ],
    "Resource": "*"
},

ポリシー設定は完了です。Amazon SES のパッケージをインストールします。
"@aws-sdk/client-ses": "^××"

コード実装

実際のLambda のindex.js のサンプルは以下です。

const {
    SESClient, SendEmailCommand
  } = require("@aws-sdk/client-ses");
const ses = new SESClient({ region: "ap-northeast-1" });
/**
 * @type {import('@types/aws-lambda').APIGatewayProxyHandler}
 */
exports.handler = async (event) => {
  const command = new SendEmailCommand({
    Destination: {
      ToAddresses: ["送信先のメールアドレス"],
    },
    Message: {
      Body: {
        Text: { Data: "Test" },
      },
      Subject: { Data: "Test Email" },
    },
    // SESのID登録されている検証済みのドメイン・メールアドレス
    Source: "送信元のメールアドレス"
  });
  try {
    let response = await ses.send(command);
    // process data.
    return response;
  }
  catch (error) {
    // error handling.
  }
  finally {
    // finally.
  }
};

テスト実施

テストには以下のようなイベントJSON を渡してみてください。

{
  "Records": [
    {
      "eventID": "1",
      "eventName": "INSERT",
      "eventSource": "aws:dynamodb",
      "awsRegion": "ap-northeast-1",
      "dynamodb": {
        "ApproximateCreationDateTime": 1631635465,
        "Keys": {
          // テーブルのフィールドに準拠
          "××": {
            "S": "××"
          }
        },
        "NewImage": {
         // テーブルのフィールドに準拠
          "××": {
            "S": "××"
          }
        },
        "OldImage": {},
        "SequenceNumber": "12345678901234567890123456789012345678901234567890",
        "SizeBytes": 123,
        "StreamViewType": "NEW_IMAGE"
      },
      "eventSourceARN": "テーブルのARN"
    }
  ]
}

これでテスト実行すると、送信先メールアドレスに設定したアドレスにメールが届きます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0