跳至內容

如何使用 Lambda 和 Amazon SES 傳送電子郵件?

3 分的閱讀內容
0

我想要使用 AWS Lambda 和 Amazon Simple Email Service (Amazon SES) 來傳送電子郵件。

簡短描述

若要使用 Lambda 和 Amazon SES 傳送電子郵件,請完成以下步驟:

  1. 為 Lambda 建立 AWS Identity and Access Management (IAM) 政策和角色,以執行 API 呼叫。
  2. 確認您的 Amazon SES 身分 (網域或電子郵件地址)。
  3. 建立或更新 Lambda 函式,其中包含透過 Amazon SES 傳送電子郵件的邏輯。

**注意:**若要在電子郵件中包含 PDF 附件,您必須使用 Amazon SES SendRawEmail API。

解決方法

建立 IAM 政策並將其附加到 Lambda 的角色以執行 API 呼叫

請完成下列步驟:

  1. 開啟 IAM console (IAM 主控台)。

  2. 使用 JSON 政策編輯器建立 IAM 政策。您建立政策時,請將下列 JSON 政策文件貼到政策編輯器:

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "ses:SendEmail",
                    "ses:SendRawEmail"
                ],
                "Resource": "*"
            }
        ]
    }
    

    **注意:**如需如何限制存取此政策的詳細資訊和範例,請參閱 SES 的範例 IAM 政策。

  3. 將 IAM 政策附加到 IAM 角色。

驗證您的 Amazon SES 身份

若要驗證網域,請參閱驗證 DNS 提供者的 DKIM 網域身分。

若要驗證電子郵件地址,請參閱驗證電子郵件地址身分。

建立或更新包含傳送電子郵件邏輯的 Lambda 函式

在以下 Node.js、Python 和 Ruby Lambda 函式程式碼範例中,根據需要將這些變數替換為您的環境:

  • 將 us-west-2 替換為您已驗證的 Amazon SES 身分所在的 AWS 區域。
  • 將 "RecipientEmailAddress", ... 替換為您想要傳送電子郵件的一個或多個電子郵件地址。
  • 將 SourceEmailAddress 替換為您已驗證的 Amazon SES 寄件者電子郵件地址,或經過 Amazon SES 驗證網域中的任何電子郵件地址。或者,編輯訊息內文 (「測試」) 和主旨行 (「測試電子郵件」)。

**注意:**您也可以在慣用的支援執行時期中設計自己的 Lambda 函式程式碼。

請完成下列步驟:

  1. 開啟 Lambda console (Lambda 主控台),然後選擇 Functions (函式)。

  2. 如果您還沒有這樣做,請建立 Lambda 函式。
    **注意:**您可以使用 Lambda 主控台,也可以建置並上傳部署套件。

  3. 選擇函式的名稱,然後選擇 Configuration (組態) 索引標籤。

  4. 在 Permissions (權限) 窗格中,檢閱函式的 Execution Role (執行角色)。

  5. 確認已列出您先前所建立具有 Amazon SES 權限的 IAM 角色。如果未列出正確的 IAM 角色,請將正確的角色指派給函式。

  6. 選擇 Code (程式碼) 索引標籤。在內建程式碼編輯器中,貼上下列其中一個函式程式碼範例。 
    Node.js 18 版及更新版本的程式碼範例:

    // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
    // SPDX-License-Identifier: Apache-2.0
    
    import { SESClient, SendEmailCommand } from "@aws-sdk/client-ses";
    const ses = new SESClient({ region: "us-west-2" });
    
    export const handler = async(event) => {
      const command = new SendEmailCommand({
        Destination: {
          ToAddresses: ["RecipientEmailAddress", ...],
        },
        Message: {
          Body: {
            Text: { Data: "Test" },
          },
    
          Subject: { Data: "Test Email" },
        },
        Source: "SourceEmailAddress",
      });
    
      try {
        let response = await ses.send(command);
        // process data.
        return response;
      }
      catch (error) {
        // error handling.
      }
      finally {
        // finally.
      }
    };

    Node.js 16 版及更早版本的程式碼範例:

     // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
    // SPDX-License-Identifier: Apache-2.0
    
    var aws = require("aws-sdk");
    var ses = new aws.SES({ region: "us-west-2" });
    exports.handler = async function (event) {
      var params = {
        Destination: {
          ToAddresses: ["RecipientEmailAddress", ...],
        },
        Message: {
          Body: {
            Text: { Data: "Test" },
          },
    
          Subject: { Data: "Test Email" },
        },
        Source: "SourceEmailAddress",
      };
    
      return ses.sendEmail(params).promise()
    };

    Python 3.9 版程式碼範例:

    import json
    import boto3
    
    client = boto3.client('ses', region_name='us-west-2')
    
    def lambda_handler(event, context):
    
        response = client.send_email(
        Destination={
            'ToAddresses': ['RecipientEmailAddress']
        },
        Message={
            'Body': {
                'Text': {
                    'Charset': 'UTF-8',
                    'Data': 'This is the message body in text format.',
                }
            },
            'Subject': {
                'Charset': 'UTF-8',
                'Data': 'Test email',
            },
        },
        Source='SourceEmailAddress'
        )
    
        print(response)
    
        return {
            'statusCode': 200,
            'body': json.dumps("Email Sent Successfully. MessageId is: " + response['MessageId'])
        }

    Ruby 2.7 版程式碼範例:

    require "aws-sdk-ses"
    
    $ses = Aws::SES::Client.new(region: "us-west-2")
    
    def lambda_handler(event:, context:)
    
      resp = $ses.send_email({
      destination: {
        to_addresses: ["RecipientEmailAddress"],
      },
      message: {
        body: {
          text: {
            charset: "UTF-8",
            data: "This is the message body in text format.",
          },
        },
        subject: {
          charset: "UTF-8",
          data: "Test email",
        },
      },
      source: "SourceEmailAddress"
    })
        { statusCode: 200, body: JSON.generate("Message Sent Successfully. #{resp.to_h} ") }
    end
  7. 選擇 Deploy (部署)。

(選用) 傳送測試電子郵件

請完成下列步驟:

  1. 開啟 Lambda console (Lambda 主控台),然後選擇您的函式。
  2. 為您的函式設定測試事件。
    **注意:**測試承載為必要項目,但未用於此程式碼範例。
  3. 選擇 Test (測試)。Lambda 會使用 Amazon SES 將測試電子郵件傳送給您的收件者。

相關資訊

使用 Amazon SES 傳送電子郵件

Amazon SES 中的身分和存取權管理

AWS 官方已更新 2 年前