

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

# 使用範本透過 Amazon SES API 傳送個人化電子郵件
<a name="send-personalized-email-api"></a>

在 Amazon SES 中，您可以使用*預存範本*或使用*內嵌範本*來傳送範本電子郵件。
+ **存放範本** – 是指使用 Amazon 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)的資源。範本包含電子郵件的主旨和內文，其中包含與寫入內容內嵌的變數 （預留位置）。呼叫 `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}}`。
     + **文字** – 電子郵件的文字內文。電子郵件用戶端未顯示 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 ]

   請注意，您在上一個步驟中建立的範本 *MyTemplate* 被參考為 `TemplateName` 參數的值。

   ```
   {
       "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}}`。
     + **文字** – 電子郵件的文字內文。電子郵件用戶端未顯示 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 ]

   請注意，您在上一個步驟中建立的範本 *MyTemplate* 被參考為 `TemplateName` 參數的值。

   ```
   {
       "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** – 在 `ReplacementTemplateData` 屬性`{}`中包含物件`ReplacementEmailContent`包含空白 JSON 物件 時將使用的鍵/值對。
   + **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}}`。
     + **文字** – 電子郵件的文字內文。電子郵件用戶端未顯示 HTML 內容的收件人將看到此版本的電子郵件。此屬性也可能包含替代標籤。
   + **TemplateData** – 包含金鑰值對，如果`ReplacementEmailContent`物件在 `ReplacementTemplateData` 屬性`{}`中包含空的 JSON 物件 ，則會使用該值對。
   + **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>

 如果您使用的是*預存範本*，也就是說，您已使用 `CreateEmailTemplate`操作搭配 SES v2 API 在 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_tw/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_tw/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
   ```

   在上述命令中，以您在上一個步驟中所建立 `update_template.json` 檔案的完整路徑取代 *path/to/update\$1template.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` 錯誤。