

 [适用于 JavaScript 的 AWS SDK V3 API 参考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)详细描述了 适用于 JavaScript 的 AWS SDK 版本 3 (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_cn/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 模块使用的 SDK JavaScript ，使用`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) 来 import/export 客户端服务对象和命令。  
这需要使用 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。
+ 邮件必须包含至少一个收件人电子邮件地址。收件人地址可以是“收件人：”地址、“抄送：”地址或“密件抄送：”地址。如果某个收件人的电子邮件地址无效（即，未使用格式 `UserName@[SubDomain.]Domain.TopLevelDomain`），则将拒绝整个邮件，即使邮件包含的其他收件人有效。
+ 邮件在“收件人：”、“抄送：”和“密件抄送：”字段中包含的收件人不能超过 50 个。如果您需要将电子邮件发送给更多的受众，可以将收件人列表划分为不超过 50 个人的组，然后多次调用 `sendEmail` 方法来发送邮件到各个组。

## 发送电子邮件
<a name="ses-examples-sendmail"></a>

在本示例中，使用 Node.js 模块通过 Amazon SES 发送电子邮件。

创建一个 `libs` 目录，然后使用文件名 `sesClient.js` 创建一个 Node.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 };
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)示例代码 GitHub。

创建文件名为 `ses_sendemail.js` 的 Node.js 模块。如前所示配置 SDK，包括安装所需的客户端和软件包。

创建一个对象以将定义要发送的电子邮件的参数值传递到 `SES` 客户端类的 `SendEmailCommand` 方法，这些参数值包括发件人和收件人地址、主题、纯文本和 HTML 格式的电子邮件正文。要调用 `SendEmailCommand` 方法，请调用一个 Amazon SES 服务对象来传递参数。

**注意**  
此示例导入并使用所需的 S AWS ervice V3 包客户端、V3 命令，并以某种 async/await 模式使用该`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 
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_sendemail.js)示例代码 GitHub。

## 使用模板发送电子邮件
<a name="ses-examples-sendtemplatedemail"></a>

在本示例中，使用 Node.js 模块通过 Amazon SES 发送电子邮件。创建文件名为 `ses_sendtemplatedemail.js` 的 Node.js 模块。如前所示配置 SDK，包括安装所需的客户端和软件包。

创建一个对象以将定义要发送的电子邮件的参数值传递到 `SES` 客户端类的 `SendTemplatedEmailCommand` 方法，这些参数值包括发件人和收件人地址、主题、纯文本和 HTML 格式的电子邮件正文。要调用 `SendTemplatedEmailCommand` 方法，请调用一个 Amazon SES 客户端服务对象来传递参数。

**注意**  
此示例导入并使用所需的 S AWS ervice V3 包客户端、V3 命令，并以某种 async/await 模式使用该`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 
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_sendtemplatedemail.js)示例代码 GitHub。

## 使用模板批量发送电子邮件
<a name="ses-examples-sendbulktemplatedemail"></a>

在本示例中，使用 Node.js 模块通过 Amazon SES 发送电子邮件。

创建一个 `libs` 目录，然后使用文件名 `sesClient.js` 创建一个 Node.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 };
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)示例代码 GitHub。

创建文件名为 `ses_sendbulktemplatedemail.js` 的 Node.js 模块。如前所示配置 SDK，包括安装所需的客户端和软件包。

创建一个对象以将定义要发送的电子邮件的参数值传递到 `SES` 客户端类的 `SendBulkTemplatedEmailCommand` 方法，这些参数值包括发件人和收件人地址、主题、纯文本和 HTML 格式的电子邮件正文。要调用 `SendBulkTemplatedEmailCommand` 方法，请调用一个 Amazon SES 服务对象来传递参数。

**注意**  
此示例导入并使用所需的 S AWS ervice V3 包客户端、V3 命令，并以某种 async/await 模式使用该`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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_sendbulktemplatedemail.js)示例代码 GitHub。