

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用模板通过 Amazon SES API 发送个性化电子邮件
<a name="send-personalized-email-api"></a>

在 Amazon SES 中，您可以使用*存储的模板*或*内联模板*来发送模板化电子邮件。
+ **存储的模板**：指通过使用 Amazon SES v2 API 中的 `CreateEmailTemplate` 操作创建并保存在 SES 中的 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Template.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Template.html) 资源。该模板包含电子邮件的主题和正文，其中包含与书面内容内联的变量（占位符）。存储模板的名称以及模板中占位符变量的动态数据在调用 `SendEmail` 或 `SendBulkEmail` v2 API 操作时提供。

  *存储的模板*可以轻松重复使用，并且可以在发送类似类型的电子邮件时为您节省时间和精力。您无需从头开始创建每封电子邮件，只需创建一次基本结构和设计，然后只需更新模板中的动态内容。
+ **内联模板**：不使用 `Template` 资源，而是在调用 `SendEmail` 或 `SendBulkEmail` v2 API 操作时，提供包含与书面内容内联的变量（占位符）的电子邮件主题和正文以及这些占位符变量的值。

  *内联模板*通过消除在 SES 账户中管理模板资源的需要来简化批量电子邮件发送过程，并通过允许您将模板内容直接包含在应用程序逻辑中来简化集成过程。它们不计入每个 20,000 个模板的限制。 AWS 区域

使用*存储的模板*时适用以下限制：
+ 每个模板中最多可以创建 20,000 个电子邮件模板 AWS 区域。
+ 每个模板的大小最多为 500 KB（包括文本和 HTML 部分）。

使用*内联模板*时适用以下限制：
+ 每个输入 JSON 文件的大小最多为 1 MB，包括文本和 HTML 部分。

以下内容适用于*存储的*和*内联模板*：
+ 可以使用的替换变量数量没有限制。
+ 在对 `SendBulkEmail` 操作的每次调用中，您可以将电子邮件发送到最多 50 个目标对象。该[https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Destination.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Destination.html)对象可以包含**ToAddresses**CcAddresses****、和中定义的多个收件人**BccAddresses**。您可以在单次 v2 API 调用中联系的目标数可能受您的账户的最大发送速率限制。有关更多信息，请参阅 [管理您的 Amazon SES 发送限制](manage-sending-quotas.md)。

本章包含使用*存储的模板*和*内联模板*的示例过程。

**注意**  
本节中的过程假定您已安装和配置 AWS CLI。有关安装和配置的更多信息 AWS CLI，请参阅《[AWS Command Line Interface 用户指南》](https://docs.aws.amazon.com/cli/latest/userguide/)。

## （可选）第 1 部分：设置呈现失败事件通知
<a name="send-personalized-email-set-up-notifications"></a>

 如果您发送一封包含无效的个性化内容的电子邮件，那么 Amazon SES 可能接受该邮件，但无法传递它。因此，如果您计划发送个性化电子邮件，则应将 SES 配置为通过 Amazon SNS 发送呈现失败事件通知。当您收到呈现失败事件通知时，您可以验证哪些邮件包含无效的内容、修复问题，然后重新发送邮件。

此部分中的过程可选，不过强烈建议使用。

**配置呈现失败事件通知**

1. 创建 Amazon SNS 主题。有关操作步骤，请参阅《Amazon Simple Notification Service 开发人员指南》**中的[创建主题](https://docs.aws.amazon.com/sns/latest/dg/sns-create-subscribe-endpoint-to-topic.html)。

1. 订阅 Amazon SNS 主题。例如，如果您希望通过电子邮件接收呈现失败通知，请使用电子邮件端点 (即，您的电子邮件地址) 订阅主题。

   有关操作步骤，请参阅《Amazon Simple Notification Service 开发人员指南》**中的[订阅主题](https://docs.aws.amazon.com/sns/latest/dg/SubscribeTopic.html)。

1. 完成[针对事件发布设置 Amazon SNS 事件目标](event-publishing-add-event-destination-sns.md)中的操作步骤来设置您的配置集，以将呈现失败事件发送到您的 Amazon SNS 主题。

## （可选）第 2 部分：创建电子邮件模板
<a name="send-personalized-email-create-template"></a>

如果您打算使用*存储的模板*，本节将向您展示如何使用 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateEmailTemplate.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateEmailTemplate.html) SES v2 API 操作来创建模板。如果您要使用*内联模板*，则可跳过该步骤。

此过程假定您已安装和配置 AWS CLI。有关安装和配置的更多信息 AWS CLI，请参阅《[AWS Command Line Interface 用户指南》](https://docs.aws.amazon.com/cli/latest/userguide/)。

**创建模板**

1. 在文本编辑器中，创建一个新文件并粘贴以下代码，根据需要对其进行自定义。

   ```
   {
       "TemplateName": "MyTemplate",
       "TemplateContent": {
           "Subject": "Greetings, {{name}}!",
           "Text": "Dear {{name}},\r\nYour favorite animal is {{favoriteanimal}}.",
           "Html": "<h1>Hello {{name}},</h1><p>Your favorite animal is {{favoriteanimal}}.</p>"
       }
   }
   ```

   此代码包含以下属性：
   + **TemplateName**— `Template` 资源的名称。当您发送电子邮件时，您将引用此名称。
   + **TemplateContent**— 用于存放以下属性的容器：
     + **主题** – 电子邮件的主题行。此属性可能包含替换标签。这些标签使用以下格式：`{{tagname}}`。当您发送电子邮件时，您可以为每个目标的 `tagname` 指定一个值。
     + **Html**：电子邮件的 HTML 正文。此属性可能包含替换标签。前面的示例包含两个标签：`{{name}}` 和 `{{favoriteanimal}}`。
     + **Text**：电子邮件的文本正文。电子邮件客户端不显示 HTML 内容的收件人将会看到此版本的电子邮件。此属性还可能包含替换标签。

1. 自定义前面的示例以满足您的需求，然后将该文件另存为 *mytemplate.json*。

1. 在命令行中键入以下命令，使用 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateEmailTemplate.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateEmailTemplate.html) v2 API 操作创建新的模板：

   ```
   aws sesv2 create-email-template --cli-input-json file://mytemplate.json
   ```

## 第 3 部分：发送个性化电子邮件
<a name="send-personalized-email-api-operations"></a>

您可以使用以下两个 SES v2 API 操作来发送使用*存储的模板*或*内联模板*的电子邮件：
+ [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html) 操作适用于向单个目标对象发送自定义电子邮件。v2 API [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Destination.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Destination.html)对象可以包含*ToAddresses*CcAddresses**、和*BccAddresses*属性。这些可以以任何组合使用，并且可以包含一个或多个将接收相同电子邮件的电子邮件地址。
+ [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendBulkEmail.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendBulkEmail.html) 操作对于在对 v2 API 的单次调用中将唯一电子邮件发送到多个目标对象很有用。

本节提供了如何通过这两个 AWS CLI 发送操作使用发送模板化电子邮件的示例。

### 将模板化电子邮件发送到单个目标对象
<a name="send-templated-email-single-destination"></a>

您可以使用 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html) 操作向单个目标对象中定义的一个或多个收件人发送电子邮件。[https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Destination.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Destination.html) 对象中的所有收件人都会收到同一电子邮件。

**将模板化电子邮件发送到单个目标对象**

1. 根据您是想使用*存储的模板*还是*内联模板*，选择相应的代码示例粘贴到文本编辑器中，并根据需要进行自定义。

------
#### [ Stored template code example ]

   请注意，您在上一步中创建的模板被引用为`TemplateName`参数的值。*MyTemplate*

   ```
   {
       "FromEmailAddress": "Mary Major <mary.major@example.com>",
       "Destination": {
           "ToAddresses": [
               "alejandro.rosalez@example.com", "jimmy.jet@example.com"
           ]
       },
       "Content": {
           "Template": {
               "TemplateName": "MyTemplate",
               "TemplateData": "{ \"name\":\"Alejandro\", \"favoriteanimal\": \"alligator\" }"
           }
       },
       "ConfigurationSetName": "ConfigSet"
   }
   ```

   此代码包含以下属性：
   + **FromEmailAddress**— 发件人的电子邮件地址。
   + **目标**-包含在*ToAddresses*、*CcAddresses*和*BccAddresses*属性中定义的电子邮件收件人的对象。这些可以以任何组合使用，并且可以包含一个或多个将接收相同电子邮件的电子邮件地址。
   + **TemplateName**— 要应用于电子邮件的`Template`资源名称。
   + **TemplateData**— 包含键值对的转义的 JSON 字符串。键对应于存储模板中 `TemplateContent` 属性定义的变量，例如 `{{name}}`。值表示用来替换变量的内容。
   + **ConfigurationSetName**— 发送电子邮件时要使用的配置集的名称。
**注意**  
我们建议您使用配置为将呈现失败事件发布到 Amazon SNS 的配置集。有关更多信息，请参阅 [（可选）第 1 部分：设置呈现失败事件通知](#send-personalized-email-set-up-notifications)。

------
#### [ Inline template code example ]

   请注意，`TemplateContent` 属性（通常会在*存储的模板*中定义）正在与 `TemplateData` 属性一起*内联*定义，这使其成为*内联模板*。

   ```
   {
       "FromEmailAddress": "Mary Major <mary.major@example.com>",
       "Destination": {
           "ToAddresses": [
               "alejandro.rosalez@example.com", "jimmy.jet@example.com"
           ]
       },
       "Content": {
           "Template": {
               "TemplateContent": {
                   "Subject": "Greetings, {{name}}!",
                   "Text": "Dear {{name}},\r\nYour favorite animal is {{favoriteanimal}}.",
                   "Html": "<h1>Hello {{name}},</h1><p>Your favorite animal is {{favoriteanimal}}.</p>"
               },
               "TemplateData": "{ \"name\":\"Alejandro\", \"favoriteanimal\": \"alligator\" }"
           }
       },
       "ConfigurationSetName": "ConfigSet"
   }
   ```

   此代码包含以下属性：
   + **FromEmailAddress**— 发件人的电子邮件地址。
   + **目标**-包含在*ToAddresses*、*CcAddresses*和*BccAddresses*属性中定义的电子邮件收件人的对象。这些可以以任何组合使用，并且可以包含一个或多个将接收相同电子邮件的电子邮件地址。
   + **TemplateContent**— 用于存放以下属性的容器：
     + **主题** – 电子邮件的主题行。此属性可能包含替换标签。这些标签使用以下格式：`{{tagname}}`。当您发送电子邮件时，您可以为每个目标的 `tagname` 指定一个值。
     + **Html**：电子邮件的 HTML 正文。此属性可能包含替换标签。前面的示例包含两个标签：`{{name}}` 和 `{{favoriteanimal}}`。
     + **Text**：电子邮件的文本正文。电子邮件客户端不显示 HTML 内容的收件人将会看到此版本的电子邮件。此属性还可能包含替换标签。
   + **TemplateData**— 包含键值对的转义的 JSON 字符串。这些键对应于本文件中 `TemplateContent` 属性定义的变量，例如 `{{name}}`。值表示用来替换变量的内容。
   + **ConfigurationSetName**— 发送电子邮件时要使用的配置集的名称。
**注意**  
我们建议您使用配置为将呈现失败事件发布到 Amazon SNS 的配置集。有关更多信息，请参阅 [（可选）第 1 部分：设置呈现失败事件通知](#send-personalized-email-set-up-notifications)。

------

1. 自定义前面的示例以满足您的需求，然后将该文件另存为 *myemail.json*。

1. 在命令行键入以下 v2 API 命令，发送电子邮件：

   ```
   aws sesv2 send-email --cli-input-json file://myemail.json
   ```

### 将模板化电子邮件发送到多个目标对象
<a name="send-templated-email-multiple-destinations"></a>

您可以使用 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendBulkEmail.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendBulkEmail.html) 操作在单次调用 SES v2 API 时向多个目标对象发送电子邮件。SES 会向每个 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Destination.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Destination.html) 对象中的收件人发送唯一的电子邮件。

**将模板化电子邮件发送到多个目标对象**

1. 根据您是想使用*存储的模板*还是*内联模板*，选择相应的代码示例粘贴到文本编辑器中，并根据需要进行自定义。

------
#### [ Stored template code example ]

   请注意，您在上一步中创建的模板被引用为`TemplateName`参数的值。*MyTemplate*

   ```
   {
       "FromEmailAddress": "Mary Major <mary.major@example.com>",
       "DefaultContent": {
           "Template": {
               "TemplateName": "MyTemplate",
               "TemplateData": "{ \"name\":\"friend\", \"favoriteanimal\":\"unknown\" }"
           }
       },
       "BulkEmailEntries": [
           {
               "Destination": {
                   "ToAddresses": [
                       "anaya.iyengar@example.com"
                   ]
               },
               "ReplacementEmailContent": {
                   "ReplacementTemplate": {
                       "ReplacementTemplateData": "{ \"name\":\"Anaya\", \"favoriteanimal\":\"angelfish\" }"
                   }
               }
           },
           {
               "Destination": {
                   "ToAddresses": [
                       "liu.jie@example.com"
                   ]
               },
               "ReplacementEmailContent": {
                   "ReplacementTemplate": {
                       "ReplacementTemplateData": "{ \"name\":\"Liu\", \"favoriteanimal\":\"lion\" }"
                   }
               }
           },
           {
               "Destination": {
                   "ToAddresses": [
                       "shirley.rodriguez@example.com"
                   ]
               },
               "ReplacementEmailContent": {
                   "ReplacementTemplate": {
                       "ReplacementTemplateData": "{ \"name\":\"Shirley\", \"favoriteanimal\":\"shark\" }"
                   }
               }
           },
           {
               "Destination": {
                   "ToAddresses": [
                       "richard.roe@example.com"
                   ]
               },
               "ReplacementEmailContent": {
                   "ReplacementTemplate": {
                       "ReplacementTemplateData": "{}"
                   }
               }
           }
       ],
       "ConfigurationSetName": "ConfigSet"
   }
   ```

   此代码包含以下属性：
   + **FromEmailAddress**— 发件人的电子邮件地址。
   + **DefaultContent**— 包含`TemplateName`和对象的 JSON `TemplateData` 对象。
   + **TemplateName**— 要应用于电子邮件的`Template`资源名称。
   + **TemplateData**— 包含键值对，如果对象在属性中包含空的 JSON `ReplacementEmailContent` 对象`{}`，则将使用这些`ReplacementTemplateData`键值对。
   + **BulkEmailEntries**— 包含一个或多个`Destination`对象的数组。
   + **目标**-包含在*ToAddresses*、*CcAddresses*和*BccAddresses*属性中定义的电子邮件收件人的对象。这些可以以任何组合使用，并且可以包含一个或多个将接收相同电子邮件的电子邮件地址。
   + **ReplacementTemplateData**— 包含键值对的转义的 JSON 字符串。键与模板中的变量（例如 `{{name}}`）对应。值表示用来替换电子邮件中的变量的内容。（如果此处的 JSON 字符串为空，由 `{}` 表示，则将使用在 `DefaultContent` 对象内的 `TemplateData` 属性中定义的键值对。）
   + **ConfigurationSetName**— 发送电子邮件时要使用的配置集的名称。
**注意**  
我们建议您使用配置为将呈现失败事件发布到 Amazon SNS 的配置集。有关更多信息，请参阅 [（可选）第 1 部分：设置呈现失败事件通知](#send-personalized-email-set-up-notifications)。

------
#### [ Inline template code example ]

   请注意，`TemplateContent` 属性（通常会在*存储的模板*中定义）正在与 `TemplateData` 属性一起*内联*定义，这使其成为*内联模板*。

   ```
   {
       "FromEmailAddress": "Mary Major <mary.major@example.com>",
       "DefaultContent": {
           "Template": {
               "TemplateContent": {
                   "Subject": "Greetings, {{name}}!",
                   "Text": "Dear {{name}},\r\nYour favorite animal is {{favoriteanimal}}.",
                   "Html": "<h1>Hello {{name}},</h1><p>Your favorite animal is {{favoriteanimal}}.</p>"
               },
               "TemplateData": "{ \"name\":\"friend\", \"favoriteanimal\":\"unknown\" }"
           }
       },
       "BulkEmailEntries": [
           {
               "Destination": {
                   "ToAddresses": [
                       "anaya.iyengar@example.com"
                   ]
               },
               "ReplacementEmailContent": {
                   "ReplacementTemplate": {
                       "ReplacementTemplateData": "{ \"name\":\"Anaya\", \"favoriteanimal\":\"angelfish\" }"
                   }
               }
           },
           {
               "Destination": {
                   "ToAddresses": [
                       "liu.jie@example.com"
                   ]
               },
               "ReplacementEmailContent": {
                   "ReplacementTemplate": {
                       "ReplacementTemplateData": "{ \"name\":\"Liu\", \"favoriteanimal\":\"lion\" }"
                   }
               }
           },
           {
               "Destination": {
                   "ToAddresses": [
                       "shirley.rodriguez@example.com"
                   ]
               },
               "ReplacementEmailContent": {
                   "ReplacementTemplate": {
                       "ReplacementTemplateData": "{ \"name\":\"Shirley\", \"favoriteanimal\":\"shark\" }"
                   }
               }
           },
           {
               "Destination": {
                   "ToAddresses": [
                       "richard.roe@example.com"
                   ]
               },
               "ReplacementEmailContent": {
                   "ReplacementTemplate": {
                       "ReplacementTemplateData": "{}"
                   }
               }
           }
       ],
       "ConfigurationSetName": "ConfigSet"
   }
   ```

   此代码包含以下属性：
   + **FromEmailAddress**— 发件人的电子邮件地址。
   + **DefaultContent**— 包含`TemplateContent`和对象的 JSON `TemplateData` 对象。
   + **TemplateContent**— 用于存放以下属性的容器：
     + **主题** – 电子邮件的主题行。此属性可能包含替换标签。这些标签使用以下格式：`{{tagname}}`。当您发送电子邮件时，您可以为每个目标的 `tagname` 指定一个值。
     + **Html**：电子邮件的 HTML 正文。此属性可能包含替换标签。前面的示例包含两个标签：`{{name}}` 和 `{{favoriteanimal}}`。
     + **Text**：电子邮件的文本正文。电子邮件客户端不显示 HTML 内容的收件人将会看到此版本的电子邮件。此属性还可能包含替换标签。
   + **TemplateData**— 包含键值对，如果对象在属性中包含空的 JSON `ReplacementEmailContent` 对象`{}`，则将使用这些`ReplacementTemplateData`键值对。
   + **BulkEmailEntries**— 包含一个或多个`Destination`对象的数组。
   + **目标**-包含在*ToAddresses*、*CcAddresses*和*BccAddresses*属性中定义的电子邮件收件人的对象。这些可以以任何组合使用，并且可以包含一个或多个将接收相同电子邮件的电子邮件地址。
   + **ReplacementTemplateData**— 包含键值对的转义的 JSON 字符串。这些键对应于本文件中 `TemplateContent` 属性定义的变量，例如 `{{name}}`。值表示用来替换电子邮件中的变量的内容。（如果此处的 JSON 字符串为空，由 `{}` 表示，则将使用在 `DefaultContent` 对象内的 `TemplateData` 属性中定义的键值对。）
   + **ConfigurationSetName**— 发送电子邮件时要使用的配置集的名称。
**注意**  
我们建议您使用配置为将呈现失败事件发布到 Amazon SNS 的配置集。有关更多信息，请参阅 [（可选）第 1 部分：设置呈现失败事件通知](#send-personalized-email-set-up-notifications)。

------

1. 更改上一步骤代码中的值以满足您的需求，然后将该文件另存为 *mybulkemail.json*。

1. 在命令行中，键入以下 v2 API 命令来发送批量电子邮件：

   ```
   aws sesv2 send-bulk-email --cli-input-json file://mybulkemail.json
   ```

# 高级电子邮件个性化
<a name="send-personalized-email-advanced"></a>

 如果您使用的是*存储的模板*，即您已通过使用 SES v2 API 的 `CreateEmailTemplate` 操作在 Amazon SES 中创建了 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Template.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Template.html) 资源，您可以利用 Handlebars 系统创建包含高级功能的模板，例如嵌套属性、数组迭代、基本条件语句和创建内联部分。本部分提供有关这些特征的一些示例。

除本部分介绍的特征以外，Handlebars 还包含许多其他特征。有关更多信息，请参阅[handlebarsjs.com](https://handlebarsjs.com/guide/builtin-helpers.html) 上的 [Built-In Helpers](http://handlebarsjs.com)。

**注意**  
为消息呈现 HTML 模板时，SES 不会转义 HTML 内容。这意味着，如果您包括用户输入的数据，例如联系人表单的用户输入数据，则需要在客户端将其转义。

**Topics**
+ [解析嵌套属性](#send-personalized-email-advanced-nested)
+ [遍历列表](#send-personalized-email-advanced-iterating)
+ [使用基本条件语句](#send-personalized-email-advanced-conditionals)
+ [创建内联部分](#send-personalized-email-advanced-inline-partials)

## 解析嵌套属性
<a name="send-personalized-email-advanced-nested"></a>

Handlebars 包括对嵌套路径的支持，这让您能够轻松组织复杂的客户数据，然后在电子邮件模板中引用这些数据。

例如，您可以将收件人数据组织到多个常规类别中。在每个类别中，您可以包含详细信息。以下代码示例显示了包含单一收件人的此种结构：

```
{
  "meta":{
    "userId":"51806220607"
  },
  "contact":{
    "firstName":"Anaya",
    "lastName":"Iyengar",
    "city":"Bengaluru",
    "country":"India",
    "postalCode":"560052"
  },
  "subscription":[
    {
      "interest":"Sports"
    },
    {
      "interest":"Travel"
    },
    {
      "interest":"Cooking"
    }
  ]
}
```

在电子邮件模板中，您可以通过以下方式引用嵌套属性：提供父属性名称，后跟句点 (.)，然后是要包含其值的属性的名称。例如，对于上例中显示的数据结构，要在电子邮件模板中包含每个收件人的名字，请在电子邮件模板中包含以下文本：`Hello {{contact.firstName}}!`

Handlebars 能够解析多层嵌套路径，这意味着您可以灵活地组织模板数据结构。

## 遍历列表
<a name="send-personalized-email-advanced-iterating"></a>

`each` 帮助程序函数可遍历数组中的项目。以下代码是一个电子邮件模板的示例，此模板使用 `each` 帮助程序函数创建每个收件人兴趣的明细列表。

```
{
  "Template": {
    "TemplateName": "Preferences",
    "SubjectPart": "Subscription Preferences for {{contact.firstName}} {{contact.lastName}}",
    "HtmlPart": "<h1>Your Preferences</h1>
                 <p>You have indicated that you are interested in receiving 
                   information about the following subjects:</p>
                 <ul>
                   {{#each subscription}}
                     <li>{{interest}}</li>
                   {{/each}}
                 </ul>
                 <p>You can change these settings at any time by visiting 
                    the <a href=https://www.example.com/prefererences/i.aspx?id={{meta.userId}}>
                    Preference Center</a>.</p>",
    "TextPart": "Your Preferences\n\nYou have indicated that you are interested in 
                 receiving information about the following subjects:\n
                 {{#each subscription}}
                   - {{interest}}\n
                 {{/each}}
                 \nYou can change these settings at any time by 
                 visiting the Preference Center at 
                 https://www.example.com/prefererences/i.aspx?id={{meta.userId}}"
  }
}
```

**重要**  
在前面的代码示例中，`HtmlPart` 和 `TextPart` 属性的值包含换行符，以便提高示例的可读性。您的模板的 JSON 文件不能在这些值中包含换行符。如果您将此示例复制并粘贴到自己的 JSON 文件中，请在继续前从 `HtmlPart` 和 `TextPart` 部分中删除换行符和多余空格。

创建模板后，您可以使用 `SendEmail` 或 `SendBulkEmail` 操作使用此模板向收件人发送电子邮件。只要每个收件人在 `Interests` 对象中至少有一个值，他们就会收到包含其兴趣明细列表的电子邮件。以下示例显示了可用于使用上述模板向多个收件人发送电子邮件的 JSON 文件：

```
{
  "Source":"Sender Name <sender@example.com>",
  "Template":"Preferences",
  "Destinations":[
    {
      "Destination":{
        "ToAddresses":[
          "anaya.iyengar@example.com"
        ]
      },
      "ReplacementTemplateData":"{\"meta\":{\"userId\":\"51806220607\"},\"contact\":{\"firstName\":\"Anaya\",\"lastName\":\"Iyengar\"},\"subscription\":[{\"interest\":\"Sports\"},{\"interest\":\"Travel\"},{\"interest\":\"Cooking\"}]}"
      },
    {
      "Destination":{ 
        "ToAddresses":[
          "shirley.rodriguez@example.com"
        ]
      },
      "ReplacementTemplateData":"{\"meta\":{\"userId\":\"1981624758263\"},\"contact\":{\"firstName\":\"Shirley\",\"lastName\":\"Rodriguez\"},\"subscription\":[{\"interest\":\"Technology\"},{\"interest\":\"Politics\"}]}"
    }
  ],
  "DefaultTemplateData":"{\"meta\":{\"userId\":\"\"},\"contact\":{\"firstName\":\"Friend\",\"lastName\":\"\"},\"subscription\":[]}"
}
```

当您使用 `SendBulkEmail` 操作向前面示例中列出的收件人发送电子邮件时，他们会收到类似下图所示示例的邮件：

![\[Preferences notification listing Sports, Travel, and Cooking as selected interests.\]](http://docs.aws.amazon.com/zh_cn/ses/latest/dg/images/send-personalized-email-advanced-condition-interest.png)


## 使用基本条件语句
<a name="send-personalized-email-advanced-conditionals"></a>

本部分基于前一部分中介绍的示例。前一部分中的示例使用 `each` 帮助程序遍历兴趣列表。但是，未指定兴趣的收件人会收到包含空列表的电子邮件。通过使用 `{{if}}` 帮助程序，您可根据模板数据中是否存在特定属性以不同方式设置电子邮件格式。以下代码使用了 `{{if}}` 帮助程序：如果 `Subscription` 数组包含任何值，则显示前一部分中的项目符号列表。如果数组为空，则显示其他的文本块。

```
{
  "Template": {
    "TemplateName": "Preferences2",
    "SubjectPart": "Subscription Preferences for {{contact.firstName}} {{contact.lastName}}",
    "HtmlPart": "<h1>Your Preferences</h1>
                 <p>Dear {{contact.firstName}},</p>
                 {{#if subscription}}
                   <p>You have indicated that you are interested in receiving 
                     information about the following subjects:</p>
                     <ul>
                     {{#each subscription}}
                       <li>{{interest}}</li>
                     {{/each}}
                     </ul>
                     <p>You can change these settings at any time by visiting 
                       the <a href=https://www.example.com/prefererences/i.aspx?id={{meta.userId}}>
                       Preference Center</a>.</p>
                 {{else}}
                   <p>Please update your subscription preferences by visiting 
                     the <a href=https://www.example.com/prefererences/i.aspx?id={{meta.userId}}>
                     Preference Center</a>.
                 {{/if}}",
    "TextPart": "Your Preferences\n\nDear {{contact.firstName}},\n\n
                 {{#if subscription}}
                   You have indicated that you are interested in receiving 
                   information about the following subjects:\n
                   {{#each subscription}}
                     - {{interest}}\n
                   {{/each}}
                   \nYou can change these settings at any time by visiting the 
                   Preference Center at https://www.example.com/prefererences/i.aspx?id={{meta.userId}}.
                 {{else}}
                   Please update your subscription preferences by visiting the 
                   Preference Center at https://www.example.com/prefererences/i.aspx?id={{meta.userId}}.
                 {{/if}}"
  }
}
```

**重要**  
在前面的代码示例中，`HtmlPart` 和 `TextPart` 属性的值包含换行符，以便提高示例的可读性。您的模板的 JSON 文件不能在这些值中包含换行符。如果您将此示例复制并粘贴到自己的 JSON 文件中，请在继续前从 `HtmlPart` 和 `TextPart` 部分中删除换行符和多余空格。

以下示例显示了可用于使用上述模板向多个收件人发送电子邮件的 JSON 文件：

```
{
  "Source":"Sender Name <sender@example.com>",
  "Template":"Preferences2",
  "Destinations":[
    {
      "Destination":{
        "ToAddresses":[
          "anaya.iyengar@example.com"
        ]
      },
      "ReplacementTemplateData":"{\"meta\":{\"userId\":\"51806220607\"},\"contact\":{\"firstName\":\"Anaya\",\"lastName\":\"Iyengar\"},\"subscription\":[{\"interest\":\"Sports\"},{\"interest\":\"Cooking\"}]}"
      },
    {
      "Destination":{ 
        "ToAddresses":[
          "shirley.rodriguez@example.com"
        ]
      },
      "ReplacementTemplateData":"{\"meta\":{\"userId\":\"1981624758263\"},\"contact\":{\"firstName\":\"Shirley\",\"lastName\":\"Rodriguez\"}}"
    }
  ],
  "DefaultTemplateData":"{\"meta\":{\"userId\":\"\"},\"contact\":{\"firstName\":\"Friend\",\"lastName\":\"\"},\"subscription\":[]}"
}
```

在此示例中，模板数据包含兴趣列表的收件人会收到与前一部分中所示示例相同的电子邮件。模板数据不包含任何兴趣的收件人会收到类似下图所示示例的电子邮件：

![\[Email message with header "Your Preferences" and text about updating subscription preferences.\]](http://docs.aws.amazon.com/zh_cn/ses/latest/dg/images/send-personalized-email-advanced-condition-nointerest.png)


## 创建内联部分
<a name="send-personalized-email-advanced-inline-partials"></a>

您可以使用内联部分简化包含重复字符串的模板。例如，您可以在模板开头添加以下代码，从而创建一个内联部分，其中包含收件人的名字和姓氏 (如果可用)：

```
{{#* inline \"fullName\"}}{{firstName}}{{#if lastName}} {{lastName}}{{/if}}{{/inline}}\n
```

**注意**  
需要使用换行符 (`\n`) 将 `{{inline}}` 块与模板内容分开。最终输出中不显示换行符。

创建 `fullName` 部分后，您可以通过在此部分的名称前加上一个大于号 (>) 并后跟一个空格来将其包含在模板中的任何位置，如下例所示：`{{> fullName}}`。内联部分不会在电子邮件部分间转移。例如，要在电子邮件的 HTML 和文本版本中使用相同的内联部分，则必须在 `HtmlPart` 和 `TextPart` 部分中都定义此部分。

遍历数组时，也可以使用内联部分。您可以使用以下代码创建使用 `fullName` 内联部分的模板。在此示例中，内联部分应用至收件人姓名和一个其他名称数组：

```
{
  "Template": {
    "TemplateName": "Preferences3",
    "SubjectPart": "{{firstName}}'s Subscription Preferences",
    "HtmlPart": "{{#* inline \"fullName\"}}
                   {{firstName}}{{#if lastName}} {{lastName}}{{/if}}
                 {{/inline~}}\n
                 <h1>Hello {{> fullName}}!</h1>
                 <p>You have listed the following people as your friends:</p>
                 <ul>
                 {{#each friends}}
                   <li>{{> fullName}}</li>
                 {{/each}}</ul>",
    "TextPart": "{{#* inline \"fullName\"}}
                   {{firstName}}{{#if lastName}} {{lastName}}{{/if}}
                 {{/inline~}}\n
                 Hello {{> fullName}}! You have listed the following people 
                 as your friends:\n
                 {{#each friends}}
                   - {{> fullName}}\n
                 {{/each}}"
  }
}
```

**重要**  
在前面的代码示例中，`HtmlPart` 和 `TextPart` 属性的值包含换行符，以便提高示例的可读性。您的模板的 JSON 文件不能在这些值中包含换行符。如果您将此示例复制并粘贴到自己的 JSON 文件中，请从这些部分中删除换行符和多余空格。

# 管理电子邮件模板
<a name="send-personalized-email-manage-templates"></a>

除了[创建电子邮件模板](send-personalized-email-api.md)之外，您还可以使用 Amazon SES v2 API 来更新或删除现有模板、列出所有现有模板或者查看模板的内容。

本节包含使用执行 AWS CLI 与 SES 模板相关的任务的过程。

**注意**  
本节中的过程假定您已安装和配置 AWS CLI。有关安装和配置的更多信息 AWS CLI，请参阅《[AWS Command Line Interface 用户指南》](https://docs.aws.amazon.com/cli/latest/userguide/)。

## 查看电子邮件模板列表
<a name="send-personalized-email-manage-templates-list"></a>

您可以使用 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListEmailTemplate.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListEmailTemplate.html) SES v2 API 操作来查看您的所有现有电子邮件模板的列表。

**查看电子邮件模板列表**
+ 在命令行输入以下命令：

  ```
  aws sesv2 list-email-templates
  ```

  如果您的 SES 账户在当前区域中存在现有电子邮件模板，那么此命令将返回类似于以下示例的响应：

  ```
  {
      "TemplatesMetadata": [
          {
              "Name": "SpecialOffers",
              "CreatedTimestamp": "2020-08-05T16:04:12.640Z"
          },
          {
              "Name": "NewsAndUpdates",
              "CreatedTimestamp": "2019-10-03T20:03:34.574Z"
          }
      ]
  }
  ```

  如果您尚未创建任何模板，那么该命令会返回没有任何成员的 `TemplatesMetadata` 对象。

## 查看特定电子邮件模板的内容
<a name="send-personalized-email-manage-templates-get"></a>

您可以使用 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetEmailTemplate.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetEmailTemplate.html) SES v2 API 操作来查看特定电子邮件模板的内容。

**查看电子邮件模板的内容**
+ 在命令行输入以下命令：

  ```
  aws sesv2 get-email-template --template-name MyTemplate
  ```

  在前面的命令中，*MyTemplate*替换为要查看的模板的名称。

  如果您提供的模板名称与 SES 账户中存在的模板匹配，那么此命令将返回类似于以下示例的响应：

  ```
  {
      "Template": {
          "TemplateName": "TestMessage",
          "SubjectPart": "Amazon SES Test Message",
          "TextPart": "Hello! This is the text part of the message.",
          "HtmlPart": "<html>\n<body>\n<h2>Hello!</h2>\n<p>This is the HTML part of the message.</p></body>\n</html>"
      }
  }
  ```

  如果您提供的模板名称与 SES 账户中存在的模板不匹配，那么该命令将返回 `NotFoundException` 错误。

## 删除电子邮件模板
<a name="send-personalized-email-manage-templates-delete"></a>

您可以使用 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteEmailTemplate.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteEmailTemplate.html) SES v2 API 操作来删除特定电子邮件模板。

**删除电子邮件模板**
+ 在命令行输入以下命令：

  ```
  aws sesv2 delete-email-template --template-name MyTemplate
  ```

  在前面的命令中，*MyTemplate*替换为要删除的模板的名称。

  此命令不提供任何输出。您可以使用[GetTemplate](#send-personalized-email-manage-templates-get)操作来验证模板是否已删除。

## 更新电子邮件模板
<a name="send-personalized-email-manage-templates-update"></a>

您可以使用 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_UpdateEmailTemplate.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_UpdateEmailTemplate.html) SES v2 API 操作来更新现有电子邮件模板。例如，如果您要更改电子邮件模板的主题行，或者如果您需要修改邮件本身的正文，那么此操作很有用。

**更新电子邮件模板**

1. 使用 `GetEmailTemplate` 命令，在命令行中输入以下命令来检索现有模板：

   ```
   aws sesv2 get-email-template --template-name MyTemplate
   ```

   在前面的命令中，*MyTemplate*替换为要更新的模板的名称。

   如果您提供的模板名称与 SES 账户中存在的模板匹配，那么此命令将返回类似于以下示例的响应：

   ```
   {
       "Template": {
           "TemplateName": "TestMessage",
           "SubjectPart": "Amazon SES Test Message",
           "TextPart": "Hello! This is the text part of the message.",
           "HtmlPart": "<html>\n<body>\n<h2>Hello!</h2>\n<p>This is the HTML part of the message.</p></body>\n</html>"
       }
   }
   ```

1. 在文本编辑器中，创建一个新文件。将上一个命令的输出粘贴到文件中。

1. 根据需要修改模板。您省略的任何行都将从模板中删除。例如，如果您只想更改模板的 `SubjectPart`，您仍然需要包含 `TextPart` 和 `HtmlPart` 属性。

   完成后，将文件另存为 `update_template.json`。

1. 在命令行输入以下命令：

   ```
   aws sesv2 update-email-template --cli-input-json file://path/to/update_template.json
   ```

   在前面的命令中，*path/to/update\$1template.json*替换为您在上一步中创建的`update_template.json`文件的路径。

   如果模板更新成功，则此命令不提供任何输出。您可以使用 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetEmailTemplate.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetEmailTemplate.html) 操作来验证模板是否已更新。

   如果您指定的模板不存在，则此命令会返回 `TemplateDoesNotExist` 错误。如果模板不包含 `TextPart` 和/或 `HtmlPart` 属性，则此命令会返回 `InvalidParameterValue` 错误。