

 [適用於 JavaScript 的 AWS SDK V3 API 參考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)詳細說明 第 3 版 適用於 JavaScript 的 AWS SDK (V3) 的所有 API 操作。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Amazon SES 傳送電子郵件
<a name="ses-examples-sending-email"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/nodeicon.png)

**這個 Node.js 程式碼範例會說明：**
+ 傳送文字或 HTML 電子郵件。
+ 根據電子郵件範本傳送電子郵件。
+ 根據電子郵件範本傳送大量電子郵件。

Amazon SES API 為您提供兩種不同的方法來傳送電子郵件，具體取決於您希望對電子郵件訊息合成的控制程度：格式化和原始。如需詳細資訊，請參閱[使用 Amazon SES API 傳送格式化的電子郵件](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-formatted.html)和[使用 Amazon SES API 傳送原始電子郵件](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html)。

## 案例
<a name="ses-examples-sending-email-scenario"></a>

在此範例中，您會使用一系列的 Node.js 模組，以多種不同方式傳送電子郵件。Node.js 模組使用適用於 JavaScript 的 SDK，使用以下`SES`用戶端類別的方法建立和使用電子郵件範本：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendEmailCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendEmailCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendTemplatedEmailCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendTemplatedEmailCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendBulkTemplatedEmailCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendBulkTemplatedEmailCommand/)

## 先決條件任務
<a name="ses-examples-sending-emails-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 電子郵件訊息傳送要求
<a name="ses-examples-sending-msail-reqs"></a>

Amazon SES 會撰寫電子郵件訊息，並立即將訊息排入佇列以供傳送。若要使用 `SendEmailCommand` 方法傳送電子郵件，您的訊息必須符合下列需求：
+ 您必須從已驗證的電子郵件地址或網域傳送訊息。如果您要使用非驗證的地址或網域來傳送電子郵件，則該操作會導致 `"Email address not verified"` 錯誤。
+ 如果您的帳戶仍在 Amazon SES 沙盒中，您只能傳送至驗證的地址或網域，或傳送至與 Amazon SES 信箱模擬器關聯的電子郵件地址。如需詳細資訊，請參閱《Amazon Simple Email Service 開發人員指南[》中的驗證電子郵件地址和網域](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html)。
+ 訊息的總大小 (包括附件) 必須小於 10 MB。
+ 該訊息至少必須含有一個收件人電子郵件地址。收件人地址可為 To (收件人)：地址、CC (副本)：地址或 BCC (密件副本)：地址。如果收件人電子郵件地址無效 （即不是 的格式`UserName@[SubDomain.]Domain.TopLevelDomain`)，即使訊息包含其他有效的收件人，也會拒絕整個訊息。
+ 訊息不能包含跨收件人：、CC： 和 BCC： 欄位的 50 個以上的收件人。若您需要傳送電子郵件訊息給更多的收件人，則您必須將收件人清單分成 50 人或更少人的群組，然後再多次呼叫 `sendEmail` 方法以傳送訊息至個別群組。

## 傳送電子郵件
<a name="ses-examples-sendmail"></a>

在此範例中，使用 Node.js 模組以搭配 Amazon SES 傳送電子郵件。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製並貼上以下程式碼，以建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_sendemail.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立 物件，以將定義要傳送之電子郵件的參數值傳遞至`SES`用戶端類別的 `SendEmailCommand`方法，包括傳送者和接收者地址、主旨和電子郵件內文。若要呼叫 `SendEmailCommand`方法，請叫用 Amazon SES 服務物件，傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *toAddress* 取代為傳送電子郵件的地址，並將 *fromAddress* 取代為傳送電子郵件的地址。

```
import { SendEmailCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createSendEmailCommand = (toAddress, fromAddress) => {
  return new SendEmailCommand({
    Destination: {
      /* required */
      CcAddresses: [
        /* more items */
      ],
      ToAddresses: [
        toAddress,
        /* more To-email addresses */
      ],
    },
    Message: {
      /* required */
      Body: {
        /* required */
        Html: {
          Charset: "UTF-8",
          Data: "HTML_FORMAT_BODY",
        },
        Text: {
          Charset: "UTF-8",
          Data: "TEXT_FORMAT_BODY",
        },
      },
      Subject: {
        Charset: "UTF-8",
        Data: "EMAIL_SUBJECT",
      },
    },
    Source: fromAddress,
    ReplyToAddresses: [
      /* more items */
    ],
  });
};

const run = async () => {
  const sendEmailCommand = createSendEmailCommand(
    "recipient@example.com",
    "sender@example.com",
  );

  try {
    return await sesClient.send(sendEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。電子郵件會排入佇列以供 Amazon SES 傳送。

```
node ses_sendemail.js 
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_sendemail.js)範例程式碼。

## 使用範本傳送電子郵件
<a name="ses-examples-sendtemplatedemail"></a>

在此範例中，使用 Node.js 模組以搭配 Amazon SES 傳送電子郵件。以檔名 `ses_sendtemplatedemail.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立一個物件以傳遞定義欲傳送電子郵件的參數值，包括寄件者和接收者地址、主旨、電子郵件本文 (純文字和 HTML 格式)，至 `SES` 用戶端類別的 `SendTemplatedEmailCommand` 方法。若要呼叫 `SendTemplatedEmailCommand`方法，請叫用 Amazon SES 用戶端服務物件，並傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *REGION* 取代為您的 AWS 區域，將 *USER* 取代為要傳送電子郵件的名稱和電子郵件地址，將 *VERIFIED\$1EMAIL* 取代為傳送電子郵件的地址，將 *TEMPLATE\$1NAME* 取代為範本的名稱。

```
import { SendTemplatedEmailCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * Replace this with the name of an existing template.
 */
const TEMPLATE_NAME = getUniqueName("ReminderTemplate");

/**
 * Replace these with existing verified emails.
 */
const VERIFIED_EMAIL = postfix(getUniqueName("Bilbo"), "@example.com");

const USER = { firstName: "Bilbo", emailAddress: VERIFIED_EMAIL };

/**
 *
 * @param { { emailAddress: string, firstName: string } } user
 * @param { string } templateName - The name of an existing template in Amazon SES.
 * @returns { SendTemplatedEmailCommand }
 */
const createReminderEmailCommand = (user, templateName) => {
  return new SendTemplatedEmailCommand({
    /**
     * Here's an example of how a template would be replaced with user data:
     * Template: <h1>Hello {{contact.firstName}},</h1><p>Don't forget about the party gifts!</p>
     * Destination: <h1>Hello Bilbo,</h1><p>Don't forget about the party gifts!</p>
     */
    Destination: { ToAddresses: [user.emailAddress] },
    TemplateData: JSON.stringify({ contact: { firstName: user.firstName } }),
    Source: VERIFIED_EMAIL,
    Template: templateName,
  });
};

const run = async () => {
  const sendReminderEmailCommand = createReminderEmailCommand(
    USER,
    TEMPLATE_NAME,
  );
  try {
    return await sesClient.send(sendReminderEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。電子郵件會排入佇列以供 Amazon SES 傳送。

```
node ses_sendtemplatedemail.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_sendtemplatedemail.js)此範例程式碼。

## 使用範本傳送大量電子郵件
<a name="ses-examples-sendbulktemplatedemail"></a>

在此範例中，使用 Node.js 模組以搭配 Amazon SES 傳送電子郵件。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製並貼上以下程式碼，以建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_sendbulktemplatedemail.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立 物件，以將定義要傳送之電子郵件的參數值傳遞至`SES`用戶端類別的 `SendBulkTemplatedEmailCommand`方法，包括傳送者和接收者地址、主旨和電子郵件內文。若要呼叫 `SendBulkTemplatedEmailCommand`方法，請叫用 Amazon SES 服務物件，傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *USERS* 取代為要傳送電子郵件的名稱和電子郵件地址、將 *VERIFIED\$1EMAIL\$11* 取代為傳送電子郵件的地址，並將 *TEMPLATE\$1NAME* 取代為範本的名稱。

```
import { SendBulkTemplatedEmailCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * Replace this with the name of an existing template.
 */
const TEMPLATE_NAME = getUniqueName("ReminderTemplate");

/**
 * Replace these with existing verified emails.
 */
const VERIFIED_EMAIL_1 = postfix(getUniqueName("Bilbo"), "@example.com");
const VERIFIED_EMAIL_2 = postfix(getUniqueName("Frodo"), "@example.com");

const USERS = [
  { firstName: "Bilbo", emailAddress: VERIFIED_EMAIL_1 },
  { firstName: "Frodo", emailAddress: VERIFIED_EMAIL_2 },
];

/**
 *
 * @param { { emailAddress: string, firstName: string }[] } users
 * @param { string } templateName the name of an existing template in SES
 * @returns { SendBulkTemplatedEmailCommand }
 */
const createBulkReminderEmailCommand = (users, templateName) => {
  return new SendBulkTemplatedEmailCommand({
    /**
     * Each 'Destination' uses a corresponding set of replacement data. We can map each user
     * to a 'Destination' and provide user specific replacement data to create personalized emails.
     *
     * Here's an example of how a template would be replaced with user data:
     * Template: <h1>Hello {{name}},</h1><p>Don't forget about the party gifts!</p>
     * Destination 1: <h1>Hello Bilbo,</h1><p>Don't forget about the party gifts!</p>
     * Destination 2: <h1>Hello Frodo,</h1><p>Don't forget about the party gifts!</p>
     */
    Destinations: users.map((user) => ({
      Destination: { ToAddresses: [user.emailAddress] },
      ReplacementTemplateData: JSON.stringify({ name: user.firstName }),
    })),
    DefaultTemplateData: JSON.stringify({ name: "Shireling" }),
    Source: VERIFIED_EMAIL_1,
    Template: templateName,
  });
};

const run = async () => {
  const sendBulkTemplateEmailCommand = createBulkReminderEmailCommand(
    USERS,
    TEMPLATE_NAME,
  );
  try {
    return await sesClient.send(sendBulkTemplateEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。電子郵件會排入佇列以供 Amazon SES 傳送。

```
node ses_sendbulktemplatedemail.js
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_sendbulktemplatedemail.js)此範例程式碼。