

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

# 透過 Amazon SES 設定電子郵件
<a name="send-email"></a>

您可以使用 Amazon SES 主控台、Amazon SES 簡易郵件傳輸協定 (SMTP) 界面或 Amazon SES API，透過 Amazon Simple Email Service (Amazon SES) 傳送電子郵件。您通常會使用主控台來傳送測試電子郵件並管理您的傳送活動。若要傳送大量電子郵件，可使用 SMTP 界面或 API。如需 Amazon SES 電子郵件定價的相關資訊，請參閱 [Amazon SES 定價](https://aws.amazon.com/ses/pricing)。
+ 如果您想要使用支援 SMTP 的軟體套件、應用程式或程式設計語言來透過 Amazon SES 傳送電子郵件，或是整合 Amazon SES 與現有的郵件伺服器，請使用 Amazon SES SMTP 界面。如需詳細資訊，請參閱[以程式設計方式透過 Amazon SES SMTP 界面來傳送電子郵件](send-using-smtp-programmatically.md)。
+ 如果您想要使用原始的 HTTP 請求呼叫 Amazon SES，請使用 Amazon SES API。如需詳細資訊，請參閱[使用 Amazon SES API 來傳送電子郵件](send-email-api.md)。

**重要**  
當您傳送電子郵件給多個收件人 (收件人包含「收件人」、「副本」和「密件副本」地址) 而 Amazon SES 的呼叫失敗時，將拒收整封電子郵件，所有收件人將不會收到該封電子郵件。因此，我們建議您每次僅傳送電子郵件給一個收件人。

# 使用 Amazon SES SMTP 界面來傳送電子郵件
<a name="send-email-smtp"></a>

若要透過 Amazon SES 傳送生產電子郵件，您可以使用簡易郵件傳輸協定 (SMTP) 界面或 Amazon SES API。如需 Amazon SES API 的詳細資訊，請參閱 [使用 Amazon SES API 來傳送電子郵件](send-email-api.md)。本節說明 SMTP 界面。

Amazon SES 使用 SMTP 來傳送電子郵件，SMTP 是網際網路上最常見的電子郵件通訊協定。您可以使用各種支援 SMTP 的程式設計語言與軟體來連線到 Amazon SES SMTP 界面，以便透過 Amazon SES 傳送電子郵件。本節說明如何取得 Amazon SES SMTP 憑證、如何使用 SMTP 界面來傳送電子郵件，以及如何設定幾套軟體和郵件伺服器來使用 Amazon SES 傳送電子郵件。

對於透過 SMTP 界面使用 Amazon SES 時可能遇到的常見問題之解決方法，請參閱 [Amazon SES SMTP 問題](troubleshoot-smtp.md)。

## 透過 SMTP 傳送電子郵件的要求
<a name="send-email-smtp-requirements"></a>

若要使用 Amazon SES SMTP 界面傳送電子郵件，您需要以下資訊：
+ SMTP 端點地址。如需 Amazon SES SMTP 端點清單，請參閱 [連線到 Amazon SES SMTP 端點](smtp-connect.md)。
+ SMTP 界面連接埠號碼。此連接埠號碼會隨連線方法而有不同。如需詳細資訊，請參閱 [連線到 Amazon SES SMTP 端點](smtp-connect.md)。
+ SMTP 使用者名稱和密碼。每個 AWS 區域的 SMTP 登入資料都是唯一的。如果您計劃使用 SMTP 界面在多個 AWS 區域中傳送電子郵件，則每個區域都需要 SMTP 憑證。
**重要**  
您的 SMTP 登入資料與您的 AWS 存取金鑰或您用來登入 Amazon SES 主控台的登入資料不同。如需如何產生 SMTP 憑證的詳細資訊，請參閱 [取得 Amazon SES SMTP 憑證](smtp-credentials.md)。
+ 可以使用 Transport Layer Security (TLS) 通訊的客戶端軟體。如需詳細資訊，請參閱 [連線到 Amazon SES SMTP 端點](smtp-connect.md)。
+ 您已向 Amazon SES 驗證的電子郵件地址。如需詳細資訊，請參閱 [在 Amazon SES 中驗證身分](verify-addresses-and-domains.md)。
+ 如果您想要傳送大量電子郵件，則需提高傳送份額。如需詳細資訊，請參閱[管理您的 Amazon SES 傳送限制](manage-sending-quotas.md)。

## 透過 SMTP 傳送電子郵件的方法
<a name="send-email-methods"></a>

您可以藉助下列任何一種方法透過 SMTP 傳送電子郵件：
+ 若要設定支援 SMTP 的軟體來透過 Amazon SES SMTP 界面傳送電子郵件，請參閱 [使用軟體套件來透過 Amazon SES 傳送電子郵件](send-email-smtp-software-package.md)。
+ 若要設計透過 Amazon SES 傳送電子郵件的應用程式，請參閱 [以程式設計方式透過 Amazon SES SMTP 界面來傳送電子郵件](send-using-smtp-programmatically.md)。
+ 若要設定現有電子郵件伺服器以透過 Amazon SES 來傳送所有外寄電子郵件，請參閱 [將 Amazon SES 與您的現有電子郵件伺服器整合](send-email-smtp-existing-server.md)。
+ 若要使用命令列來與 Amazon SES SMTP 界面互動 (這在測試時很有用)，請參閱 [使用命令列測試 Amazon SES SMTP 界面的連線](send-email-smtp-client-command-line.md)。

如需 SMTP 回應代碼的清單，請參閱 [Amazon SES 傳回的 SMTP 回應代碼](troubleshoot-smtp.md#troubleshoot-smtp-response-codes)。

## 需提供的電子郵件資訊
<a name="smtp-parameters"></a>

當您透過 SMTP 界面存取 Amazon SES 時，您的 SMTP 用戶端應用程式將組合訊息，因此您需要提供的資訊將取決於您使用的應用程式。客戶端與伺服器間的 SMTP 交換至少將需要下列內容：
+ 來源地址
+ 目的地地址
+ 訊息資料

如果您使用 SMTP 界面並已啟用意見回饋轉送功能，則您的退信、抱怨和傳遞通知將傳送至「寄件人」地址。不會使用任何您指定的「回覆至」(Reply-To) 地址。



# 取得 Amazon SES SMTP 憑證
<a name="smtp-credentials"></a>

您需要 Amazon SES SMTP 憑證才能存取 SES SMTP 界面。

您用來透過 SES SMTP 界面傳送電子郵件的登入資料對於每個 AWS 區域都是唯一的。如果您在多個區域中使用 SES SMTP 界面來傳送電子郵件，您必須為每個區域產生一組 SMTP 憑證。

您的 SMTP 密碼與您的 AWS 私密存取金鑰不同。如需憑證的詳細資訊，請參閱 [Amazon SES 憑證的類型](send-email-concepts-credentials.md)。

**注意**  
如需目前可用 SMTP 端點的清單，請參閱 中的 [SMTP 端點](https://docs.aws.amazon.com/general/latest/gr/ses.html#ses_smtp_endpoints)*AWS 一般參考*。

## 使用 SES 主控台來取得 SES SMTP 憑證
<a name="smtp-credentials-console"></a>

**需求**  
IAM 使用者可以建立 SES SMTP 憑證，但該使用者的政策必須提供他們使用 IAM 的許可，因為 SES SMTP 憑證是使用 IAM 建立的。您的 IAM 政策必須允許您執行下列 IAM 動作：`iam:ListUsers`、`iam:CreateUser`、`iam:CreateAccessKey` 及 `iam:PutUserPolicy`。如果您嘗試使用主控台建立 SES SMTP 登入資料，而您的 IAM 使用者沒有這些許可，您會看到錯誤，指出您的帳戶*「未獲授權執行 iam：ListUsers."*

**重要**  
上述參考的 IAM 動作具有最高 IAM 層級[的許可管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_understand-policy-summary-access-level-summaries.html#access_policies_access-level)存取層級，因為它提供在服務中授予或修改資源許可的許可。因此，為了提高 AWS 帳戶的安全性，強烈建議您限制或定期監控這些政策，包括許可管理存取層級分類。

**若要建立 SMTP 登入資料**

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/ses/](https://console.aws.amazon.com/ses/) 的 Amazon SES 主控台。

1. 選擇左側導覽窗格中的 **SMTP settings** (SMTP 憑證) - 此將開啟 **Simple Mail Transfer Protocol (SMTP) settings** (簡易郵件傳輸協定 (SMTP) 設定) 頁面。

1. 選擇右上角中的 **Create SMTP Credentials** (建立 SMTP 憑證) - IAM 主控台隨即開啟。

1. (選用) 若您需要檢視、編輯或刪除已建立的 SMTP 使用者，請選擇右下角的 **Manage my existing SMTP credentials** (管理我現有的 SMTP 認證) - IAM 主控台隨即開啟。下列這些程序會提供管理 SMTP 憑證的詳細資訊。

1. 針對**為 SMTP 建立使用者**，在**使用者名稱**欄位中輸入您 SMTP 使用者的名稱。或者，您可以使用此欄位提供的預設值。當您完成時，請選擇右下角的**建立使用者**。

1. 在 *SMTP 密碼*底下選取**顯示**，您的 SMTP 憑證會顯示在畫面上。

1. 選擇**下載 .csv 檔案**來下載這些憑證，或將它們複製並存放在安全的地方，因為關閉此對話方塊之後，您就無法檢視或儲存憑證。

1. 選擇**返回 SES 主控台**。

您可以檢視您建立的 SMTP 憑證清單，方法是在 IAM 主控台的 **Access management (存取管理)** 下方使用此程序，然後選擇 **Users (使用者)**，接著使用搜尋列尋找您已指派 SMTP 憑證的所有使用者。

您也可以使用 IAM 主控台來刪除現有的 SMTP 使用者。若要進一步瞭解刪除使用者，請參閱 *IAM 入門指南*中的[管理 IAM 使用者](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html)。

若您要變更 SMTP 密碼，請刪除 IAM 主控台中您現有的 SMTP 使用者。然後完成上述程序，以產生一組新的 SMTP 憑證。

## 透過轉換現有的登入資料來取得 SES SMTP AWS 登入資料
<a name="smtp-credentials-convert"></a>

如果您有使用 IAM 界面設定的使用者，您可以從使用者的憑證衍生使用者的 SES SMTP AWS 憑證。

**重要**  
請勿使用臨時 AWS 登入資料來衍生 SMTP 登入資料。SES SMTP 界面不支援從暫時安全憑證產生的 SMTP 憑證。

**若要讓 IAM 使用者使用 SES SMTP 界面傳送電子郵件**

1. 請依照這些程序，使用本節提供的演算法，從使用者的登入資料衍生使用者的 SMTP AWS 登入資料。

   由於您從 AWS 登入資料開始，SMTP 使用者名稱與 AWS 存取金鑰 ID 相同，因此您只需要產生 SMTP 密碼。

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 的 IAM 主控台。

1. 在**存取管理**下，選擇**政策**後面接著**建立政策**。

1. 在**政策編輯器**中，選取 **JSON**，並在編輯器中移除任何範例程式碼。

1. 將下列許可政策貼到編輯器：

------
#### [ JSON ]

****  

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

------

1. 選取**下一步**，然後在**政策名稱**欄位中輸入 `AmazonSesSendingAccess`，後面接著**建立政策**。

1. 在**存取管理**下，選擇**使用者群組**後面接著**建立群組**。

1. `AWSSESSendingGroupDoNotRename` 在**使用者群組名稱**欄位中輸入 。

1. 從將使用者新增至群組資料表中選取 SMTP **使用者，將其新增至群組**。

1. 從連接許可`AmazonSesSendingAccess`政策資料表中選取先前建立的政策，接著選取**建立使用者群組**，以連接該政策。 ****

如需搭配 IAM 使用 SES 的詳細資訊，請參閱 [Amazon SES 中的身分和存取管理](control-user-access.md)。

**注意**  
雖然您可以為任何 IAM 使用者產生 SES SMTP 憑證，我們建議您在產生 SMTP 憑證時建立另一個 IAM 使用者。如需為何針對特定用途建立使用者是最佳實務的資訊，請前往 [IAM 最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPractices.html)。

下列虛擬程式碼顯示將 AWS 私密存取金鑰轉換為 SES SMTP 密碼的演算法。

```
 1. // Modify this variable to include your AWS secret access key
 2. key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
 3.             
 4. // Modify this variable to refer to the AWS Region that you want to use to send email.
 5. region = "us-west-2";
 6.             
 7. // The values of the following variables should always stay the same.
 8. date = "11111111";
 9. service = "ses";
10. terminal = "aws4_request";
11. message = "SendRawEmail";
12. version = 0x04;
13. 
14. kDate = HmacSha256(date, "AWS4" + key);
15. kRegion = HmacSha256(region, kDate);
16. kService = HmacSha256(service, kRegion);
17. kTerminal = HmacSha256(terminal, kService);
18. kMessage = HmacSha256(message, kTerminal);
19. signatureAndVersion = Concatenate(version, kMessage);
20. smtpPassword = Base64(signatureAndVersion);
```

某些程式設計語言包含可用於將 IAM 私密存取金鑰轉換為 SMTP 密碼的程式庫。本節包含程式碼範例，您可以使用 Python 將 AWS 私密存取金鑰轉換為 SES SMTP 密碼。

**注意**  
以下範例使用 Python 3.6 引入的 **f 字串**，如果使用舊版本將無法運作。
在下列範例中，SMTP\$1REGIONS 清單只是一個範例，您的實際區域清單可能會更短或更長，具體取決於您計劃傳送電子郵件的區域，因為每個區域都需要 SMTP 登入資料 AWS 區域。

------
#### [ Python ]

```
#!/usr/bin/env python3

import hmac
import hashlib
import base64
import argparse

SMTP_REGIONS = [
    "us-east-2",  # US East (Ohio)
    "us-east-1",  # US East (N. Virginia)
    "us-west-2",  # US West (Oregon)
    "ap-south-1",  # Asia Pacific (Mumbai)
    "ap-northeast-2",  # Asia Pacific (Seoul)
    "ap-southeast-1",  # Asia Pacific (Singapore)
    "ap-southeast-2",  # Asia Pacific (Sydney)
    "ap-northeast-1",  # Asia Pacific (Tokyo)
    "ca-central-1",  # Canada (Central)
    "eu-central-1",  # Europe (Frankfurt)
    "eu-west-1",  # Europe (Ireland)
    "eu-west-2",  # Europe (London)
    "eu-south-1",  # Europe (Milan)
    "eu-north-1",  # Europe (Stockholm)
    "sa-east-1",  # South America (Sao Paulo)
    "us-gov-west-1",  # AWS GovCloud (US)
    "us-gov-east-1",  # AWS GovCloud (US)
]

# These values are required to calculate the signature. Do not change them.
DATE = "11111111"
SERVICE = "ses"
MESSAGE = "SendRawEmail"
TERMINAL = "aws4_request"
VERSION = 0x04


def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()


def calculate_key(secret_access_key, region):
    if region not in SMTP_REGIONS:
        raise ValueError(f"The {region} Region doesn't have an SMTP endpoint.")

    signature = sign(("AWS4" + secret_access_key).encode("utf-8"), DATE)
    signature = sign(signature, region)
    signature = sign(signature, SERVICE)
    signature = sign(signature, TERMINAL)
    signature = sign(signature, MESSAGE)
    signature_and_version = bytes([VERSION]) + signature
    smtp_password = base64.b64encode(signature_and_version)
    return smtp_password.decode("utf-8")


def main():
    parser = argparse.ArgumentParser(
        description="Convert a Secret Access Key to an SMTP password."
    )
    parser.add_argument("secret", help="The Secret Access Key to convert.")
    parser.add_argument(
        "region",
        help="The AWS Region where the SMTP password will be used.",
        choices=SMTP_REGIONS,
    )
    args = parser.parse_args()
    print(calculate_key(args.secret, args.region))


if __name__ == "__main__":
    main()
```

若要使用此指令碼取得您的 SMTP 密碼，請將上述程式碼儲存為 `smtp_credentials_generate.py`。然後，在命令列中執行以下命令：

```
python path/to/smtp_credentials_generate.py wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY us-east-1
```

針對上述命令執行以下事項：
+ 以您儲存 `smtp_credentials_generate.py` 的位置路徑取代 *path/to/*。
+ *wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY* 將 取代為您要轉換為 SMTP 密碼的私密存取金鑰。
+ 將 *us-east-1* 取代為您要使用 SMTP 登入資料的 AWS 區域。

這個指令碼執行成功時，唯一的輸出便是您的 SMTP 密碼。

------

## 將 SMTP 使用者從現有的內嵌政策遷移至群組政策 （安全建議）
<a name="migrate-inline-policy-to-group"></a>

**重要**  
如果您在 2024 年 9 月 6 日之前建立 SES SMTP 登入資料，則內嵌政策和標籤已連接至您的 SMTP 使用者。SES 正在偏離內嵌政策，並鼓勵您執行與安全建議相同的動作。

將 SMTP 使用者從現有的內嵌政策遷移至群組政策之前，您必須先使用 SES 許可政策建立 IAM 使用者群組，以取代內嵌政策。如果您已建立此 IAM 使用者群組，或已針對您自 2024 年 9 月 6 日起建立的 SMTP 登入資料自動建立，您可以直接跳至下列程序中*的步驟 10*。

**從現有的內嵌政策遷移至受管群組**

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 的 IAM 主控台。

1. 在**存取管理**下，選擇**政策**後面接著**建立政策**。

1. 在**政策編輯器**中，選取 **JSON**，並在編輯器中移除任何範例程式碼。

1. 將下列許可政策貼到編輯器：

------
#### [ JSON ]

****  

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

------

1. 選取**下一步**，然後在`AmazonSesSendingAccess`**政策名稱**欄位中輸入 ，後面接著**建立政策**。

1. 在**存取管理**下，選擇**使用者群組**後面接著**建立群組**。

1. `AWSSESSendingGroupDoNotRename` 在**使用者群組名稱**欄位中輸入 。

1. 從將使用者新增至群組資料表中選取 SMTP **使用者，將其新增至群組**。

1. 從連接許可`AmazonSesSendingAccess`政策資料表中選取先前建立的政策，接著選取建立**使用者群組，以連接先前建立**的政策。 ****

   現在您已使用 SES 許可政策建立 IAM 使用者群組，您可以將 SMTP 使用者從目前的內嵌政策遷移至此群組政策，如其餘步驟所述。

1. 在**存取管理**下，選擇**使用者**，然後選擇您要遷移的 SMTP 使用者。

1. 選取**群組**索引標籤，然後選擇**將使用者新增至群組**。

1. 選取`AWSSESSendingGroupDoNotRename`群組 **（後面接著新增使用者至群組）**。

1. 選取**許可**索引標籤，並確認**政策名稱**欄中有兩個列與 `AmazonSesSendingAccess` 一起列出，一個與*內嵌*在一起，另一個與**透過連接**欄中列出的*群組`AWSSESSendingGroupDoNotRename`*一起列出。

1. 僅選取`AmazonSesSendingAccess`**政策名稱**欄中包含的資料列，以及在**透過連接**資料欄中*內嵌*的資料列，後面接著**移除**，然後使用**移除政策**進行確認。

   確認**透過連接**資料欄中具有*群組`AWSSESSendingGroupDoNotRename`*的資料列仍然存在。

1. 選取**標籤**索引標籤，後面接著**管理標籤**。

1. 在**金鑰**欄中選取包含 *InvokedBy* 的資料列旁的**移除**，並在**值**欄中選取 *SESConsole*，然後選取**儲存變更**。

**重要**  
`AmazonSesSendingAccess` 政策 （做為內嵌或群組政策或兩者） 必須保持連接到 SMTP 使用者，以確保其傳送不會受到影響。只有在群組政策連接到您的使用者之後，才能移除內嵌政策。

# 連線到 Amazon SES SMTP 端點
<a name="smtp-connect"></a>

若要使用 Amazon SES SMTP 界面來傳送電子郵件，您必須連接到 SMTP 端點。如需 Amazon SES SMTP 端點的完整清單，請參閱 *AWS 一般參考* 中的 [Amazon Simple Email Service 端點和配額](https://docs.aws.amazon.com/general/latest/gr/ses.html)。

Amazon SES SMTP 端點要求所有連線皆使用 Transport Layer Security (TLS) 加密。(請注意，TLS 通常是指前置工作通訊協定的名稱 SSL。) Amazon SES 支援透過兩種機制來建立 TLS 加密連線：STARTTLS 和 TLS Wrapper。請參閱軟體的說明文件，以判斷是否支援 STARTTLS、TLS Wrapper 或兩者皆支援。

根據預設，Amazon Elastic Compute Cloud (Amazon EC2) 調節透過連接埠 25 傳送電子郵件流量。為了避免透過 SMTP 端點從 EC2 傳送電子郵件時發生逾時，請訂閱 [移除電子郵件傳送限制的請求](https://aws-portal.amazon.com/gp/aws/html-forms-controller/contactus/ec2-email-limit-rdns-request) 來移除調節。或者，您可以使用不同的連接埠傳送電子郵件，或使用 [Amazon VPC 端點](send-email-set-up-vpc-endpoints.md)。

有關 SMTP 連線問題，請參閱 [SMTP 問題](troubleshoot-smtp.md)。

## STARTTLS
<a name="smtp-connect-starttls"></a>

STARTTLS 是一種將未加密連線升級為加密連線的方法。各種通訊協定適用的 STARTTLS 版本各不相同，[RFC 3207](https://www.ietf.org/rfc/rfc3207.txt) 中定義有 SMTP 版本的規範。

若要設定 STARTTLS 連線，SMTP 用戶端需連接到連接埠 25、587 或 2587 上的 Amazon SES SMTP 端點、發出 EHLO 命令，接著等待伺服器宣布支援 STARTTLS SMTP 擴充。然後，用戶端將發出 STARTTLS 命令並啟動 TLS 溝通。當溝通完成時，用戶端會透過新的加密連線來發出 EHLO 命令，然後 SMTP 工作階段將繼續正常運作。

## TLS Wrapper
<a name="smtp-connect-tlswrapper"></a>

TLS Wrapper (也稱為 SMTPS 或 Handshake 通訊協定) 是一種無需先建立未加密連線來啟動加密連線的方法。使用 TLS Wrapper 時，Amazon SES SMTP 端點不會執行 TLS 交涉：使用 TLS 連接端點、在整個對話過程中使用 TLS 來繼續等工作都是用戶端的責任。TLS Wrapper 是較舊的通訊協定，但是仍受許多用戶端支援。

若要設定 TLS Wrapper 連線，SMTP 用戶端需連接到連接埠 465 或 2465 上的 Amazon SES SMTP 端點。伺服器出示其憑證、用戶端發出 EHLO 命令，接著 SMTP 工作階段將繼續正常運作。

# 使用軟體套件來透過 Amazon SES 傳送電子郵件
<a name="send-email-smtp-software-package"></a>

有多種支援透過 SMTP 傳送電子郵件的商用與開放原始碼軟體套件。以下是一些範例：
+ 部落格平台
+ RSS 彙總工具
+ 清單管理軟體
+ 工作流程系統

您可以設定任何支援 SMTP 的軟體來透過 Amazon SES SMTP 界面傳送電子郵件。如需有關如何為特定軟體套件設定 SMTP 的詳細資訊，請參閱該軟體文件。

下列程序說明如何使用 JIRA 來設定 Amazon SES 傳送，JIRA 是熱門的問題追蹤解決方案。有了這項組態，JIRA 可以在軟體問題的狀態發生變化時透過電子郵件通知使用者。

**設定 JIRA 以使用 Amazon SES 傳送電子郵件**

1. 若要使用您的 Web 瀏覽器，請使用管理員憑證登入 JIRA。

1. 在瀏覽器視窗中，選擇 **Administration (管理)**。

1. 在 **System (系統)** 選單上，選擇 **Mail (電子郵件)**。

1. 在 **Mail administration (電子郵件管理)** 頁面上，選擇 **Mail Servers (電子郵件伺服器)**。

1. 選擇 **Configure new SMTP mail server (設定新的 SMTP 電子郵件伺服器)**。

1. 在 **Add SMTP Mail Server (新增 SMTP 電子郵件伺服器)** 表單上，填寫下列欄位：

   1. **Name (名稱)** - 此伺服器的描述名稱。

   1. **From address (寄件人地址)** - 傳出電子郵件的地址。您必須使用 Amazon SES 來驗證此電子郵件地址才能由此傳出。如需驗證的詳細資訊，請參閱 [在 Amazon SES 中驗證身分](verify-addresses-and-domains.md)。

   1. **Email prefix (電子郵件字首)** - JIRA 在傳送前對每個主旨行加入的字首字串。

   1. **Protocol (通訊協定)** - 選擇 **SMTP**。
**注意**  
如果您無法使用此設定來連接到 Amazon SES，請嘗試使用 **SECURE\$1SMTP**。

   1. **Hostname (主機名稱)** - 請參閱 [連線到 Amazon SES SMTP 端點](smtp-connect.md) 以取得 Amazon SES SMTP 端點清單。例如，如果您想要在美國西部 (奧勒岡) 區域中使用 Amazon SES 端點，主機名稱就是 *email-smtp.us-west-2.amazonaws.com*。

   1. **SMTP port (SMTP 連接埠)** - 25、587 或 2587 (使用 STARTTLS 連接) 或 465、2465 (使用 TLS Wrapper 連接)。

   1. **TLS** - 選取此核取方塊。

   1. **User Name (使用者名稱)** – 您的 SMTP 使用者名稱。

   1. **Password (密碼)** - 您的 SMTP 密碼。

   您可以檢視下圖中 TLS Wrapper 的設定。  
![\[適用於 JIRA 的 SMTP 電子郵件組態\]](http://docs.aws.amazon.com/zh_tw/ses/latest/dg/images/SMTP_jira.png)

1. 選擇 **Test Connection (測試連接)**。如果 JIRA 透過 Amazon SES 傳送的測試電子郵件成功送達，即表示您的設定已完成。

# 以程式設計方式透過 Amazon SES SMTP 界面來傳送電子郵件
<a name="send-using-smtp-programmatically"></a>

若要使用 Amazon SES SMTP 界面傳送電子郵件，您可以使用支援 SMTP 的程式設計語言、電子郵件伺服器或應用程式。開始之前，請完成 [設定 Amazon Simple Email Service](setting-up.md) 中的任務。您也需要提供下列資訊：
+ 您的 Amazon SES SMTP 憑證可讓您連線到 Amazon SES SMTP 端點。若要取得您的 Amazon SES SMTP 憑證，請參閱 [取得 Amazon SES SMTP 憑證](smtp-credentials.md)。
**重要**  
您的 SMTP 登入資料與您的 AWS 登入資料不同。如需憑證的詳細資訊，請參閱 [Amazon SES 憑證的類型](send-email-concepts-credentials.md)。
+ SMTP 端點地址。若需 Amazon SES SMTP 端點清單，請參閱「[連線到 Amazon SES SMTP 端點](smtp-connect.md)」。
+ Amazon SES SMTP 界面連接埠號碼，取決於連線方法。如需詳細資訊，請參閱[連線到 Amazon SES SMTP 端點](smtp-connect.md)。

## 程式碼範例
<a name="send-email-smtp-code-examples"></a>

使用支援 SMTP 的程式設計語言來存取 Amazon SES SMTP 界面。您提供 Amazon SES SMTP 主機名稱和連接埠號碼與您的 SMTP 憑證，然後使用程式設計語言的一般 SMTP 函數來傳送電子郵件。

Amazon Elastic Compute Cloud (Amazon EC2) 預設限制透過連接埠 25 傳送電子郵件流量。為了避免透過 SMTP 端點從 Amazon EC2 傳送電子郵件時發生逾時，您可以請求移除這些限制。如需詳細資訊，請參閱[如何從 Amazon EC2 執行個體或 AWS Lambda 函數移除連接埠 25 的限制？](https://aws.amazon.com/premiumsupport/knowledge-center/ec2-port-25-throttle/) AWS 知識中心的 。

對於 Java 和 PHP，本節中的程式碼範例使用連接埠 587 來避免這個問題。

**注意**  
在這些教學課程中，可傳送電子郵件給自己，以確認是否成功收到。如需進一步試驗或負載測試，請使用 Amazon SES 信箱模擬器。傳送到信箱模擬器的電子郵件不會計入您的傳送份額或退信率與投訴率。如需詳細資訊，請參閱[手動使用信箱模擬器](send-an-email-from-console.md#send-email-simulator)。

**選取程式設計語言以檢視該語言的範例：**

**警告**  
Amazon SES 不建議使用靜態登入資料。請參閱 ，[AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)了解如何透過從原始程式碼中移除硬式編碼憑證來改善您的安全狀態。本教學課程僅用於在非生產環境中測試 Amazon SES SMTP 界面。

------
#### [ Java ]

此範例使用 [Eclipse IDE](http://www.eclipse.org/) 以及 [JavaMail API](https://github.com/javaee/javamail/releases) 來使用 SMTP 界面透過 Amazon SES 來傳送電子郵件。

執行下列程序前，請先完成 [設定 Amazon Simple Email Service](setting-up.md) 中的任務。

**透過 Java 使用 Amazon SES SMTP 界面傳送電子郵件**

1. 在 Web 瀏覽器中，前往 [JavaMail GitHub 頁面](https://github.com/javaee/javamail/releases)。在**資產**下，選擇 **javax.mail.jar** 以下載最新版本的 JavaMail。
**重要**  
此教學課程需要 JavaMail 版本 1.5 或更新版本。這些程序已使用 JavaMail 1.6.1 版進行測試。

1. 在 Web 瀏覽器中，前往[雅加達啟用 GitHub 頁面](https://github.com/eclipse-ee4j/jaf/releases)，然後在 [JavaBeans 啟用架構 1.2.1 最終版本](https://github.com/eclipse-ee4j/jaf/releases/tag/1.2.1)下，下載 **jakarta.activation.jar**

1. 執行以下步驟以在 Eclipse 中建立專案：

   1. 啟動 Eclipse。

   1. 在 Eclipse 中，選擇 **File (檔案)**，選擇 **New (新增)**，然後選擇 **Java Project (Java 專案)**。

   1. 在 **Create a Java Project (建立 Java 專案)** 對話方塊中，輸入專案名稱，然後選擇 **Next (下一步)**。

   1. 在 **Java Settings (Java 設定)** 對話方塊中，選擇 **Libraries (程式庫)** 標籤。

   1. 選取 **Classpath**，然後使用新增外部 ** JARs** 按鈕新增兩個外部 jar 檔案 **javax.mail.jar** 和 **jakarta.activation.jar**。

   1. 選擇 **Add External JARs (新增外部 JAR)**。

   1. 瀏覽至您下載 JavaMail 的資料夾。選擇檔案 `javax.mail.jar`，然後選擇 **Open (開啟)**。

   1. 在 **Java Settings (Java 設定)** 對話方塊中，選擇 **Finish (完成)**。

1. 在 Eclipse 的 **Package Explorer (套件總管)** 視窗中，展開您的專案。

1. 在您的專案下，以滑鼠右鍵按一下 **src** 目錄，選擇 **New (新建)**，然後選擇 **Class (類別)**。

1. 在 **New Java Class (新 Java 類別)** 對話方塊的 **Name (名稱)** 欄位中，輸入 `AmazonSESSample`，然後選擇 **Finish (完成)**。

1. 使用下列程式碼取代 **AmazonSESSample.java** 的完整內容：

   ```
     1. import java.util.Properties;
     2. 
     3. import javax.mail.Message;
     4. import javax.mail.Session;
     5. import javax.mail.Transport;
     6. import javax.mail.internet.InternetAddress;
     7. import javax.mail.internet.MimeMessage;
     8. 
     9. public class AmazonSESSample {
    10. 
    11.     // Replace sender@example.com with your "From" address.
    12.     // This address must be verified.
    13.     static final String FROM = "sender@example.com";
    14.     static final String FROMNAME = "Sender Name";
    15.     
    16.     // Replace recipient@example.com with a "To" address. If your account 
    17.     // is still in the sandbox, this address must be verified.
    18.     static final String TO = "recipient@example.com";
    19.     
    20.     // Replace smtp_username with your Amazon SES SMTP user name.
    21.     static final String SMTP_USERNAME = "smtp_username";
    22.       
    23.     // The name of the Configuration Set to use for this message.
    24.     // If you comment out or remove this variable, you will also need to
    25.     // comment out or remove the header below.
    26.     static final String CONFIGSET = "ConfigSet";
    27.     
    28.     // Amazon SES SMTP host name. This example uses the US West (Oregon) region.
    29.     // See https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html#region-endpoints
    30.     // for more information.
    31.     static final String HOST = "email-smtp.us-west-2.amazonaws.com";
    32.     
    33.     // The port you will connect to on the Amazon SES SMTP endpoint. 
    34.     static final int PORT = 587;
    35.     
    36.     static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)";
    37.     
    38.     static final String BODY = String.join(
    39.             System.getProperty("line.separator"),
    40.             "<h1>Amazon SES SMTP Email Test</h1>",
    41.             "<p>This email was sent with Amazon SES using the ", 
    42.             "<a href='https://github.com/javaee/javamail'>Javamail Package</a>",
    43.             " for <a href='https://www.java.com'>Java</a>."
    44.         );
    45. 
    46.     public static void main(String[] args) throws Exception {
    47. 
    48.         // Create a Properties object to contain connection configuration information.
    49.         Properties props = System.getProperties();
    50.         props.put("mail.transport.protocol", "smtp");
    51.         props.put("mail.smtp.port", PORT); 
    52.         props.put("mail.smtp.starttls.enable", "true");
    53.         props.put("mail.smtp.auth", "true");
    54. 
    55.         // Create a Session object to represent a mail session with the specified properties. 
    56.         Session session = Session.getDefaultInstance(props);
    57. 
    58.         // Create a message with the specified information. 
    59.         MimeMessage msg = new MimeMessage(session);
    60.         msg.setFrom(new InternetAddress(FROM,FROMNAME));
    61.         msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
    62.         msg.setSubject(SUBJECT);
    63.         msg.setContent(BODY,"text/html");
    64.         
    65.         // Add a configuration set header. Comment or delete the 
    66.         // next line if you are not using a configuration set
    67.         msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGSET);
    68.             
    69.         // Create a transport.
    70.         Transport transport = session.getTransport();
    71. 
    72.         // Get the password 
    73.         String SMTP_PASSWORD = fetchSMTPPasswordFromSecureStorage();
    74.                     
    75.         // Send the message.
    76.         try
    77.         {
    78.             System.out.println("Sending...");
    79.             
    80.             // Connect to Amazon SES using the SMTP username and password you specified above.
    81.             transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
    82.             
    83.             // Send the email.
    84.             transport.sendMessage(msg, msg.getAllRecipients());
    85.             System.out.println("Email sent!");
    86.         }
    87.         catch (Exception ex) {
    88.             System.out.println("The email was not sent.");
    89.             System.out.println("Error message: " + ex.getMessage());
    90.         }
    91.         finally
    92.         {
    93.             // Close and terminate the connection.
    94.             transport.close();
    95.         }
    96.     }
    97. 
    98.     static String fetchSMTPPasswordFromSecureStorage() {
    99.         /* IMPLEMENT THIS METHOD */
   100.         // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/
   101.     }
   102. }
   ```

1. 在 **AmazonSESSample.java** 中，將下列電子郵件地址取代為您自己的值：
**重要**  
電子郵件地址會區分大小寫。請確認此地址與您已完成驗證的地址完全相同。
   + *sender@example.com* – 以您的「寄件者」電子郵件地址取代 。執行此程式前，須先驗證此地址。如需詳細資訊，請參閱[在 Amazon SES 中驗證身分](verify-addresses-and-domains.md)。
   + *recipient@example.com* – 將 取代為您的「收件人」電子郵件地址。如果您的帳戶仍在沙盒中，您必須在使用前先驗證這個地址。如需詳細資訊，請參閱[請求生產存取權 （移出 Amazon SES 沙盒）](request-production-access.md)。

1. 在 **AmazonSESSample.java** 中，將下列項目取代為您自己的值：
   + *smtp\$1username* – 將 取代為您的 SMTP 使用者名稱憑證。請注意您的 SMTP 使用者名稱憑證為包含字母與數字的 20 字元字串，而非容易理解的名稱。
   + *smtp\$1password* – 實作 ``fetchSMTPPasswordFromSecureStorage``來擷取密碼。

1. （選用） 如果您想要在 *email-smtp.us-west-2.amazonaws.com* AWS 區域 以外的 中使用 Amazon SES SMTP 端點，請將 變數的值變更為您要使用的`HOST`端點。如需可使用 Amazon SES 的區域清單，請參閱 *AWS 一般參考* 中的 [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)。

1. （選用） 如果您想要在傳送此電子郵件時使用組態集，請將變數 *ConfigSet* 的值變更為組態集的名稱。如需組態集的詳細資訊，請參閱 [使用 Amazon SES 中的組態集](using-configuration-sets.md)。

1. 儲存 **AmazonSESSample.java**。

1. 若要建置專案，請選擇 **Project (專案)**，然後選擇 **Build Project (建置專案)**。(如果此選項為停用，則您可能已啟用自動建立。)

1. 若要啟動程式並傳送電子郵件，請選擇 **Run (執行)**，然後再次選擇 **Run (執行)**。

1. 檢閱輸出。如果電子郵件已成功傳送，主控台會顯示*「電子郵件已傳送！」* 否則會顯示錯誤訊息。

1. 登入至收件人地址的電子郵件用戶端。可以看到您已傳送的訊息。

------
#### [ PHP  ]

此範例使用 PHPMailer 類別來使用 SMTP 界面透過 Amazon SES 傳送電子郵件。

在執行下列程序前，必須先完成 [設定 Amazon Simple Email Service](setting-up.md) 中的任務。除了設定 Amazon SES 之外，您還必須完成下列先決條件，才能使用 PHP 傳送電子郵件：

**事前準備：**
+ **安裝 PHP** – PHP 可在 https：//[http://php.net/downloads.php](https://php.net/downloads.php) 取得。安裝 PHP 後，在環境變數中將路徑新增至 PHP，即可透過任何命令提示來執行 PHP。
+ **安裝 Composer 相依性管理員** – 安裝 Composer 相依性管理員後，您可以下載並安裝 PHPMailer 類別及其相依性。若要安裝 Composer，請依照 [https://getcomposer.org/download](https://getcomposer.org/download) 中的安裝說明。
+ **安裝 PHPMailer 類別** – 安裝 Composer 之後，請執行下列命令來安裝 PHPMailer：

  ```
  path/to/composer require phpmailer/phpmailer
  ```

  在上述命令中，以安裝 Composer 的路徑取代 *path/to/*。

**透過 PHP 使用 Amazon SES SMTP 界面傳送電子郵件**

1. 建立名為 **amazon-ses-smtp-sample.php** 的檔案。使用文字編輯器開啟檔案，並貼上以下程式碼：

   ```
    1. <?php
    2. 
    3. // Import PHPMailer classes into the global namespace
    4. // These must be at the top of your script, not inside a function
    5. use PHPMailer\PHPMailer\PHPMailer;
    6. use PHPMailer\PHPMailer\Exception;
    7. 
    8. // If necessary, modify the path in the require statement below to refer to the
    9. // location of your Composer autoload.php file.
   10. require 'vendor/autoload.php';
   11. 
   12. // Replace sender@example.com with your "From" address.
   13. // This address must be verified with Amazon SES.
   14. $sender = 'sender@example.com';
   15. $senderName = 'Sender Name';
   16. 
   17. // Replace recipient@example.com with a "To" address. If your account
   18. // is still in the sandbox, this address must be verified.
   19. $recipient = 'recipient@example.com';
   20. 
   21. // Replace smtp_username with your Amazon SES SMTP user name.
   22. $usernameSmtp = 'smtp_username';
   23. 
   24. // Specify a configuration set. If you do not want to use a configuration
   25. // set, comment or remove the next line.
   26. $configurationSet = 'ConfigSet';
   27. 
   28. // If you're using Amazon SES in a region other than US West (Oregon),
   29. // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
   30. // endpoint in the appropriate region.
   31. $host = 'email-smtp.us-west-2.amazonaws.com';
   32. $port = 587;
   33. 
   34. // The subject line of the email
   35. $subject = 'Amazon SES test (SMTP interface accessed using PHP)';
   36. 
   37. // The plain-text body of the email
   38. $bodyText =  "Email Test\r\nThis email was sent through the
   39.     Amazon SES SMTP interface using the PHPMailer class.";
   40. 
   41. // The HTML-formatted body of the email
   42. $bodyHtml = '<h1>Email Test</h1>
   43.     <p>This email was sent through the
   44.     <a href="https://aws.amazon.com/ses">Amazon SES</a> SMTP
   45.     interface using the <a href="https://github.com/PHPMailer/PHPMailer">
   46.     PHPMailer</a> class.</p>';
   47. 
   48. $mail = new PHPMailer(true);
   49. 
   50. try {
   51.     // Specify the SMTP settings.
   52.     $mail->isSMTP();
   53.     $mail->setFrom($sender, $senderName);
   54.     $mail->Username   = $usernameSmtp;
   55.     $mail->Password   = fetchSMTPPasswordFromSecureStorage();
   56.     $mail->Host       = $host;
   57.     $mail->Port       = $port;
   58.     $mail->SMTPAuth   = true;
   59.     $mail->SMTPSecure = 'tls';
   60.     $mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configurationSet);
   61. 
   62.     // Specify the message recipients.
   63.     $mail->addAddress($recipient);
   64.     // You can also add CC, BCC, and additional To recipients here.
   65. 
   66.     // Specify the content of the message.
   67.     $mail->isHTML(true);
   68.     $mail->Subject    = $subject;
   69.     $mail->Body       = $bodyHtml;
   70.     $mail->AltBody    = $bodyText;
   71.     $mail->Send();
   72.     echo "Email sent!" , PHP_EOL;
   73. } catch (phpmailerException $e) {
   74.     echo "An error occurred. {$e->errorMessage()}", PHP_EOL; //Catch errors from PHPMailer.
   75. } catch (Exception $e) {
   76.     echo "Email not sent. {$mail->ErrorInfo}", PHP_EOL; //Catch errors from Amazon SES.
   77. }
   78. function fetchSMTPPasswordFromSecureStorage() {
   79. /* IMPLEMENT THIS METHOD */
   80. // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/
   81. }
   82. 
   83. ?>
   ```

1. 在 **amazon-ses-smtp-sample.php** 中，將以下內容取代為您自己的值：
   + *sender@example.com* – 以您已透過 Amazon SES 驗證的電子郵件地址取代 。如需詳細資訊，請參閱[驗證身分](verify-addresses-and-domains.md)。Amazon SES 中的電子郵件地址會區分大小寫。請確認您輸入的地址與您已完成驗證的地址完全相同。
   + *recipient@example.com* – 將 取代為收件人的地址。如果您的帳戶仍在沙盒中，您必須在使用前先驗證這個地址。如需詳細資訊，請參閱 [請求生產存取權 （移出 Amazon SES 沙盒）](request-production-access.md)。請確認您輸入的地址與您已完成驗證的地址完全相同。
   + *smtp\$1username* – 將 取代為您從 Amazon SES 主控台的 SMTP [設定頁面取得的 SMTP](https://console.aws.amazon.com/ses/home?#smtp-settings:) 使用者名稱憑證。此憑證與您的 AWS 存取金鑰 ID **不同**。請注意您的 SMTP 使用者名稱憑證為包含字母與數字的 20 字元字串，而非容易理解的名稱。
   + *smtp\$1password* – 實作 ``fetchSMTPPasswordFromSecureStorage``來擷取密碼。
   + （選用） *ConfigSet* – 如果您想要在傳送此電子郵件時使用組態集，請將此值取代為組態集的名稱。如需組態集的詳細資訊，請參閱 [使用 Amazon SES 中的組態集](using-configuration-sets.md)。
   + （選用） *email-smtp.us-west-2.amazonaws.com*：// – 如果您想要在美國西部 （奧勒岡） 以外的區域中使用 Amazon SES SMTP 端點，請將此端點取代為您要使用的區域中的 Amazon SES SMTP 端點。如需可使用 Amazon SES 之 AWS 區域 的 SMTP 端點 URLs 清單，請參閱《》中的 [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)*AWS 一般參考*。

1. 儲存 **amazon-ses-smtp-sample.php**。

1. 若要執行程式，請在與 **amazon-ses-smtp-sample.php** 相同的目錄中開啟命令提示，然後輸入 **php amazon-ses-smtp-sample.php**。

1. 檢閱輸出。如果電子郵件已成功傳送，主控台會顯示*「電子郵件已傳送！」* 否則會顯示錯誤訊息。

1. 登入收件人地址的電子郵件用戶端。可以看到您已傳送的訊息。

------

# 將 Amazon SES 與您的現有電子郵件伺服器整合
<a name="send-email-smtp-existing-server"></a>

若您目前正管理自己的電子郵件伺服器，您可以使用 Amazon SES SMTP 端點來將您所有的外寄電子郵件傳送到 Amazon SES。無需修改現有的電子郵件用戶端和應用程式；轉換至 Amazon SES 將不會對它們產生影響。

有數個郵件傳輸代理程式 (MTA) 支援透過 SMTP 轉傳功能來傳送電子郵件。本節提供一般指導準則，說明如何使用 Amazon SES SMTP 界面來設定部分常用的 MTA 來傳送電子郵件。

Amazon SES SMTP 端點要求所有連線皆使用 Transport Layer Security (TLS) 加密。

**Topics**
+ [透過 Postfix 整合 Amazon SES](postfix.md)
+ [將 Amazon SES 與 Sendmail 整合](send-email-sendmail.md)
+ [將 Amazon SES 與 Microsoft Windows Server IIS SMTP 整合](send-email-windows-server.md)

# 透過 Postfix 整合 Amazon SES
<a name="postfix"></a>

Postfix 為普及度最高的 Sendmail 訊息傳輸代理程式 (MTA) 之替代程式。如需 Postfix 的資訊，請前往 [http://www.postfix.org](http://www.postfix.org)。此主題中的程序將搭配 Linux、macOS 或 Unix 操作。

**注意**  
Postfix 是第三方應用程式，並非由 Amazon Web Services 開發或支援。本節中的程序僅供參考，如有變更，恕不另行通知。

## 先決條件
<a name="send-email-postfix-prereqs"></a>

在完成本節的程序前，您必須先執行下列任務：
+ 若您的系統已安裝 Sendmail 應用程式，請先解除安裝。完成此步驟的程序因您使用的作業系統而異。
**重要**  
以下提到的 *sendmail* 是指 Postfix 命令 `sendmail`，不要與 Sendmail 應用程式混淆。
+ 安裝 Postfix。完成此步驟的程序因您使用的作業系統而異。
+ 安裝 SASL 身分驗證套件。完成此步驟的程序因您使用的作業系統而異。例如，如果您使用 RedHat 為基礎的系統，您應該安裝 `cyrus-sasl-plain` 套件。如果您使用 Debian 或 Ubuntu 為基礎的系統，您應該安裝 `libsasl2-modules` 套件。
+ 驗證用於傳送電子郵件的電子郵件地址或網域。如需詳細資訊，請參閱[建立電子郵件地址身分](creating-identities.md#verify-email-addresses-procedure)。
+ 如果您的帳戶仍在沙盒內，您只能將電子郵件傳送到已驗證的電子郵件地址。如需詳細資訊，請參閱「[請求生產存取權 （移出 Amazon SES 沙盒）](request-production-access.md)」。

## 設定 Postfix
<a name="send-email-postfix"></a>

完成以下步驟來設定您的郵件伺服器，以使用 Postfix 來透過 Amazon SES 傳送電子郵件。

**若要設定 Postfix**

1. 在命令列中輸入以下命令：

   ```
   sudo postconf -e "relayhost = [email-smtp.us-west-2.amazonaws.com]:587" \
   "smtp_sasl_auth_enable = yes" \
   "smtp_sasl_security_options = noanonymous" \
   "smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd" \
   "smtp_use_tls = yes" \
   "smtp_tls_security_level = secure" \
   "smtp_tls_note_starttls_offer = yes"
   ```
**注意**  
如果您在美國西部 （奧勒岡） 以外的 AWS 區域使用 Amazon SES，請將上述命令中的 *email-smtp.us-west-2.amazonaws.com* 取代為適當區域的 SMTP 端點。如需詳細資訊，請參閱[區域和 Amazon SES](regions.md)。

1. 在文字編輯器中開啟檔案 `/etc/postfix/master.cf`。搜尋下列項目：

   ```
   -o smtp_fallback_relay=
   ```

   如果發現此項目，請在程式碼的開頭放置 `#` (雜湊) 字元來註解它。儲存並關閉檔案。

   否則請移至下一個步驟 (如果此項目不存在)。

1. 在文字編輯器中開啟檔案 `/etc/postfix/sasl_passwd`。如果檔案不存在，請建立檔案。

1. 新增下行到 `/etc/postfix/sasl_passwd`：

   ```
   [email-smtp.us-west-2.amazonaws.com]:587 SMTPUSERNAME:SMTPPASSWORD
   ```
**注意**  
將 *SMTPUSERNAME* 和 *SMTPPASSWORD* 取代為您的 SMTP 登入憑證。您的 SMTP 登入憑證與您的 AWS 存取金鑰 ID 和私密存取金鑰不同。如需憑證的詳細資訊，請參閱 [取得 Amazon SES SMTP 憑證](smtp-credentials.md)。  
如果您在美國西部 （奧勒岡） 以外的 AWS 區域使用 Amazon SES，請將上述範例中的 *email-smtp.us-west-2.amazonaws.com* 取代為適當區域的 SMTP 端點。如需詳細資訊，請參閱[區域和 Amazon SES](regions.md)。

   儲存並關閉 `sasl_passwd`。

1. 在命令提示中，輸入下列命令來建立包含您 SMTP 登入資料的雜湊對應資料庫檔案：

   ```
   sudo postmap hash:/etc/postfix/sasl_passwd
   ```

1. (選用) 您在前面步驟中建立的 `/etc/postfix/sasl_passwd` 和 `/etc/postfix/sasl_passwd.db` 檔案不會加密。由於這些檔案包含您的 SMTP 登入資料，我們建議您修改檔案的所有權和權限，以限制存取。若要限制存取這些檔案：

   1. 在命令提示中，輸入下列命令來變更檔案的所有權：

      ```
      sudo chown root:root /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
      ```

   1. 在命令提示中，輸入下列命令來變更檔案的許可，只讓根使用者可以讀取或寫入它們：

      ```
      sudo chmod 0600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
      ```

1. 告訴 Postfix 可在哪裡找到憑證授權機構憑證 (需要驗證 Amazon SES 伺服器憑證)。在此步驟中使用的命令將根據您的作業系統而有不同。
   + 如果您使用 Amazon Linux、Red Hat Enterprise Linux 或相關的分佈類型，請輸入下列命令：

     ```
     sudo postconf -e 'smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt'
     ```
   + 如果您使用 Ubuntu 或相關的分佈，請輸入下列命令：

     ```
     sudo postconf -e 'smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt'
     ```
   + 如果您使用 macOS，您可以從您的系統金鑰鏈產生憑證。若要產生憑證，請在命令列輸入下列命令：

     ```
     sudo security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain | sudo tee /etc/ssl/certs/ca-bundle.crt > /dev/null
     ```

     產生憑證之後，請輸入下列命令：

     ```
     sudo postconf -e 'smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt'
     ```

1. 輸入以下命令啟動 Postfix 伺服器 (如果伺服器已在執行，則重新載入組態設定)：

   ```
   sudo postfix start; sudo postfix reload
   ```

1. 在命令列輸入下列行並在各行末按 Enter 鍵以傳送測試電子郵件。以您的寄件者電子郵件地址取代 *sender@example.com*。寄件者地址需經驗證才可搭配 Amazon SES 使用。以目標地址取代 *recipient@example.com*。如果您的帳戶仍在沙盒中，也必須驗證收件人地址。最後，訊息的最後一行必須包含單一句號 (.)，沒有其他內容。

   ```
   sendmail -f sender@example.com recipient@example.com
   From: Sender Name <sender@example.com>
   Subject: Amazon SES Test                
   This message was sent using Amazon SES.                
   .
   ```

1. 檢查與收件人地址相關的信箱。如未收到電子郵件，請檢查您的垃圾郵件資料夾。如果仍找不到電子郵件，請檢查用以傳送電子郵件的系統郵件日誌 (通常位於 `/var/log/maillog`) 以取得詳細資訊。

## 進階用法範例
<a name="send-email-postfix-advanced"></a>

此範例說明如何使用[組態集](using-configuration-sets.md)來傳送電子郵件，以及使用 MIME 分段編碼來傳送訊息的純文字和 HTML 版本，同時包含附件。它也包含一個[連結標籤](faqs-metrics.md#sending-metric-faqs-clicks-q5)，可用於分類點選事件。電子郵件的內容中於外部檔案中指定，因此您不需要在 Postfix 工作階段中手動輸入指令。

**若要使用 Postfix 傳送分段 MIME 電子郵件**

1. 在文字編輯器中，建立名為 `mime-email.txt` 的新檔案。

1. 在文字檔案中，貼上下列內容以適用於帳戶的值來取代紅字值：

   ```
   X-SES-CONFIGURATION-SET: ConfigSet
   From:Sender Name <sender@example.com>
   Subject:Amazon SES Test
   MIME-Version: 1.0
   Content-Type: multipart/mixed; boundary="YWVhZDFlY2QzMGQ2N2U0YTZmODU"
   
   --YWVhZDFlY2QzMGQ2N2U0YTZmODU
   Content-Type: multipart/alternative; boundary="3NjM0N2QwMTE4MWQ0ZTg2NTYxZQ"
   
   --3NjM0N2QwMTE4MWQ0ZTg2NTYxZQ
   Content-Type: text/plain; charset=UTF-8
   Content-Transfer-Encoding: quoted-printable
   
   Amazon SES Test
   
   This message was sent from Amazon SES using the SMTP interface.
   
   For more information, see:
   http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-smtp.html
   
   --3NjM0N2QwMTE4MWQ0ZTg2NTYxZQ
   Content-Type: text/html; charset=UTF-8
   Content-Transfer-Encoding: quoted-printable
   
   <html>
     <head>
   </head>
     <body>
       <h1>Amazon SES Test</h1>
         <p>This message was sent from Amazon SES using the SMTP interface.</p>
         <p>For more information, see
         <a ses:tags="samplekey0:samplevalue0;samplekey1:samplevalue1;" 
         href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-smtp.html">
         Using the Amazon SES SMTP Interface to Send Email</a> in the <em>Amazon SES
         Developer Guide</em>.</p>
     </body>
   </html>
   --3NjM0N2QwMTE4MWQ0ZTg2NTYxZQ--
   --YWVhZDFlY2QzMGQ2N2U0YTZmODU
   Content-Type: application/octet-stream
   MIME-Version: 1.0
   Content-Transfer-Encoding: base64
   Content-Disposition: attachment; filename="customers.txt"
   
   SUQsRmlyc3ROYW1lLExhc3ROYW1lLENvdW50cnkKMzQ4LEpvaG4sU3RpbGVzLENh
   bmFkYQo5MjM4OSxKaWUsTGl1LENoaW5hCjczNCxTaGlybGV5LFJvZHJpZ3VleixV
   bml0ZWQgU3RhdGVzCjI4OTMsQW5heWEsSXllbmdhcixJbmRpYQ==
   --YWVhZDFlY2QzMGQ2N2U0YTZmODU--
   ```

   儲存並關閉檔案。

1. 在命令列中輸入以下命令。以您的電子郵件地址取代 *sender@example.com*，以收件人的電子郵件地址取代 *recipient@example.com*。

   ```
   sendmail -f sender@example.com recipient@example.com < mime-email.txt
   ```

   如果命令執行成功，將不提供任何輸出便直接關閉。

1. 請檢查您的收件匣，注意是否有電子郵件。如未遞送訊息，請檢查系統的郵件日誌。

# 將 Amazon SES 與 Sendmail 整合
<a name="send-email-sendmail"></a>

Sendmail 於 1980 年代初期推出，功能也持續改善。這是一個有大型使用者社群之靈活且可設定的訊息傳輸代理程式 (MTA)。Sendmail 是 Proofpoint 於 2013 年取得，但 Proofpoint 持續提供 Sendmail 的開放原始碼版本。您可以從 Proofpoint 網站下載[開放原始碼版本的 Sendmail](https://www.proofpoint.com/us/open-source-email-solution)，或是透過大多數 Linux 發行套件的套件管理工具取得。

本節中的程序示範如何設定 Sendmail 來透過 Amazon SES 傳送電子郵件。此程序已經在執行 Ubuntu 18.04.2 LTS 的伺服器上進行過測試。

**注意**  
Sendmail 是第三方應用程式，並非由 Amazon Web Services 開發或支援。本節中的程序僅供參考，如有變更，恕不另行通知。

## 先決條件
<a name="send-email-sendmail-prerequisites"></a>

在完成本節中的程序前，您應該先完成下列步驟：
+ 在您的伺服器上安裝 Sendmail 套件。
**注意**  
根據您使用的作業系統發行套件，您可能也需要安裝下列套件：`sendmail-cf`、`m4` 及 `cyrus-sasl-plain`。
+ 驗證身分以做為您的「寄件人」地址。如需詳細資訊，請參閱[建立電子郵件地址身分](creating-identities.md#verify-email-addresses-procedure)。

  如果您的帳戶在 Amazon SES 沙盒中，您還必須驗證傳送電子郵件的地址。如需詳細資訊，請參閱[請求生產存取權 （移出 Amazon SES 沙盒）](request-production-access.md)。

如果您使用 Amazon SES 從 Amazon EC2 執行個體傳送電子郵件，您也應該完成下列步驟：
+ 您可能需要將彈性 IP 地址指派給 Amazon EC2 執行個體，接收電子郵件供應商才能接受您的電子郵件。如需詳細資訊，請參閱《[Amazon EC2 使用者指南》中的 Amazon EC2 彈性 IP 地址](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)。 *Amazon EC2 *
+ Amazon Elastic Compute Cloud (Amazon EC2) 預設限制透過連接埠 25 傳送電子郵件流量。為了避免透過 SMTP 端點從 Amazon EC2 傳送電子郵件時發生逾時，您可以請求移除這些限制。如需詳細資訊，請參閱[如何從 Amazon EC2 執行個體或 AWS Lambda 函數移除連接埠 25 的限制？](https://aws.amazon.com/premiumsupport/knowledge-center/ec2-port-25-throttle/) AWS 知識中心的 。

  或者，您可以修改本節中的程序，使用連接埠 587 而非連接埠 25。

## 設定 Sendmail
<a name="send-email-sendmail-procedure"></a>

完成本節中的步驟，將 Sendmail 設定為使用 Amazon SES 傳送電子郵件。

**重要**  
本節中的程序假設您想要在美國西部 （奧勒岡） 使用 Amazon SES AWS 區域。若想要使用不同的區域，請以所需區域的 SMTP 端點取代此程序中所有的 *email-smtp.us-west-2.amazonaws.com* 執行個體。如需可使用 Amazon SES 的 之 SMTP 端點 URL 清單，請參閱 *AWS 一般參考* 中的 [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)。

**設定 Sendmail**

1. 在檔案編輯器中開啟檔案 `/etc/mail/authinfo`。如果檔案不存在，請先建立檔案。

   將下行新增至 */etc/mail/authinfo*：

   ```
   AuthInfo:email-smtp.us-west-2.amazonaws.com "U:root" "I:smtpUsername" "P:smtpPassword" "M:PLAIN"
   ```

   在上述範例中，進行下列變更：
   + 以您想要使用的 Amazon SES SMTP 端點取代 *email-smtp.us-west-2.amazonaws.com*。
   + 以您的 Amazon SES SMTP 使用者名稱取代 *smtpUsername*。
   + 以您的 Amazon SES SMTP 密碼取代 *smtpPassword*。
**注意**  
您的 SMTP 登入憑證與您的 AWS 存取金鑰 ID 和私密存取金鑰不同。如需取得 SMTP 登入憑證的詳細資訊，請參閱 [取得 Amazon SES SMTP 憑證](smtp-credentials.md)。

   完成時，請儲存 `authinfo`。

1. 在命令列輸入下列命令來產生 `/etc/mail/authinfo.db` 檔案：

   ```
   sudo sh -c 'makemap hash /etc/mail/authinfo.db < /etc/mail/authinfo'
   ```

1. 在命令列輸入下列命令以新增轉發至 Amazon SES SMTP 端點的支援。

   ```
   sudo sh -c 'echo "Connect:email-smtp.us-west-2.amazonaws.com RELAY" >> /etc/mail/access'
   ```

   在上述命令中，以您想要使用的 Amazon SES SMTP 端點地址取代 *email-smtp.us-west-2.amazonaws.com*。

1. 在命令列輸入下列命令來重新產生 */etc/mail/access.db*：

   ```
   sudo sh -c 'makemap hash /etc/mail/access.db < /etc/mail/access'
   ```

1. 在命令列輸入下列命令來建立 `sendmail.cf` 和 `sendmail.mc` 檔案的備份：

   ```
   sudo sh -c 'cp /etc/mail/sendmail.cf /etc/mail/sendmail_cf.backup && cp /etc/mail/sendmail.mc /etc/mail/sendmail_mc.backup'
   ```

1. 在 */etc/mail/sendmail.mc* 檔案中的任何 `MAILER()` 定義前新增下列行。

   ```
   define(`SMART_HOST', `email-smtp.us-west-2.amazonaws.com')dnl
   define(`RELAY_MAILER_ARGS', `TCP $h 25')dnl
   define(`confAUTH_MECHANISMS', `LOGIN PLAIN')dnl
   FEATURE(`authinfo', `hash -o /etc/mail/authinfo.db')dnl
   MASQUERADE_AS(`example.com')dnl
   FEATURE(masquerade_envelope)dnl
   FEATURE(masquerade_entire_domain)dnl
   ```

   針對上述文字執行以下事項：
   + 以您想要使用的 Amazon SES SMTP 端點取代 *email-smtp.us-west-2.amazonaws.com*。
   + 以您要用來傳送電子郵件的網域取代 *example.com*。

   完成後，儲存檔案。
**注意**  
Amazon EC2 預設會限制通過連接埠 25 的通訊。如果您使用在 Amazon EC2 執行個體中使用 Sendmail，您應該完成[請求移除電子郵件傳送限制](https://aws-portal.amazon.com/gp/aws/html-forms-controller/contactus/ec2-email-limit-rdns-request)。

1. 在命令列輸入下列命令，將 *sendmail.cf* 設為可寫入狀態：

   ```
   sudo chmod 666 /etc/mail/sendmail.cf
   ```

1. 在命令列輸入下列命令來重新產生 *sendmail.cf*：

   ```
   sudo sh -c 'm4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf'
   ```
**注意**  
如果發生「找不到命令」和「沒有此類檔案或目錄」等錯誤，請確定您已經在系統中安裝 `m4` 及 `sendmail-cf` 套件。

1. 在命令列輸入下列命令，將 *sendmail.cf* 的權限重新設定為唯讀狀態：

   ```
   sudo chmod 644 /etc/mail/sendmail.cf
   ```

1. 在命令列輸入下列命令來重新設定 Sendmail：

   ```
   sudo /etc/init.d/sendmail restart
   ```

   *根據 Linux 或 Sendmail 的版本，如果上述內容無法運作，請嘗試以下操作:*

   ```
   sudo su service sendmail restart
   ```

1. 完成下列步驟來傳送測試電子郵件：

   1. 在命令列輸入下列命令。

      ```
      /usr/sbin/sendmail -vf sender@example.com recipient@example.com
      ```

      以您的寄件者電子郵件地址取代 *sender@example.com*。以收件者地址取代 *recipient@example.com*。完成後，按下 Enter。

   1. 輸入下列訊息內容。按下每行尾端的 Enter。

      ```
      From: sender@example.com
      To: recipient@example.com
      Subject: Amazon SES test email
      
      This is a test message sent from Amazon SES using Sendmail.
      ```

      當您完成輸入內容的電子郵件時，按下 Ctrl\$1D 傳送郵件。

1. 檢查電子郵件的收件人電子郵件客戶端。如果您找不到電子郵件，請檢查垃圾郵件資料夾。如果您仍然找不到電子郵件，請檢查郵件伺服器上的 Sendmail 日誌。此日誌通常位於 */var/log/mail.log* 或 */var/log/maillog*。

# 將 Amazon SES 與 Microsoft Windows Server IIS SMTP 整合
<a name="send-email-windows-server"></a>

您可設定 Microsoft Windows Server 的 IIS SMTP 伺服器來透過 Amazon SES 傳送電子郵件。這些指示是在 Amazon EC2 執行個體上使用 Microsoft Windows Server 2022 撰寫。您可以在 Microsoft Windows Server 2016 上使用相同的組態。

**注意**  
Windows Server 是第三方應用程式，並非由 Amazon Web Services 開發或支援。本節中的程序僅供參考，如有變更，恕不另行通知。

**將 Amazon SES 與 Microsoft Windows Server IIS SMTP 伺服器整合**

1. 首先，使用下列指示設定 Microsoft Windows Server 2022。

   1. 從 [Amazon EC2 管理主控台](https://console.aws.amazon.com/ec2/home)啟動新的 Microsoft Windows Server 2022 Base Amazon EC2 執行個體。

   1. 連線到執行個體，並遵循 [Amazon EC2 Windows 執行個體入門](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/EC2Win_GetStarted.html)中的指示，使用遠端桌面登入執行個體。

   1. 啟動伺服器管理員儀表板。

   1. 安裝 **Web Server (Web 伺服器)** 角色。請務必包含 **IIS 10 管理相容性工具 **(**Web Server** 核取方塊下的選項）。

   1. 安裝 **SMTP Server (SMTP 伺服器)** 功能。

1. 接著，使用以下說明來設定 IIS SMTP 服務。

   1.  返回伺服器管理員儀表板。

   1. 從**工具**功能表中，選擇**網際網路資訊服務 (IIS) 10.0 Manager。**

   1. 在 **SMTP Virtual Server \$11 (SMTP 虛擬伺服器 \$11)** 上按一下滑鼠右鍵，然後選取 **Properties (屬性)**。

   1. 在 **Access (存取)** 標籤的 **Relay Restrictions (轉送限制)** 下，選擇 **Relay (轉送)**。

   1. 在 **Relay Restrictions (轉送限制)** 對話方塊中，選擇 **Add(新增)**。

   1. 在 **Single Computer (單一電腦)** 下，輸入 **127.0.0.1** 做為 IP 地址。現在您已獲得此伺服器的存取權限，可透過 IIS SMTP 服務轉送電子郵件至 Amazon SES。

      在此步驟中，我們假設您的電子郵件在此伺服器上產生。如果產生電子郵件的應用程式在另一個伺服器上執行，您必須在 IIS SMTP 中提供該伺服器轉送權限。
**注意**  
若要將 SMTP 轉送延伸到私有子網路，針對 **Relay Restriction (轉送限制)**，請使用 **Single Computer (單一電腦)** 127.0.0.1 和 **Group of Computers (電腦群組)** 172.1.1.0 – 255.255.255.0 (位於網路遮罩區段)。針對 **Connection (連線)**，請使用 **Single Computer (單一電腦)** 127.0.0.1 和 **Group of Computers (電腦群組)** 172.1.1.0 – 255.255.255.0 (位於網路遮罩區段)。

1. 最後，使用下列說明來設定伺服器以透過 Amazon SES 傳送電子郵件。

   1. 返回 **SMTP Virtual Server \$11 Properties (SMTP 虛擬伺服器 \$11 屬性)** 對話方塊，然後選擇 **Delivery (交付)** 標籤。

   1. 在 **Delivery (交付)** 標籤上，選擇 **Outbound Security (對外安全性)**。

   1. 選擇 **Basic Authentication** (基本身分驗證)，然後輸入您的 Amazon SES SMTP 憑證。您可使用 [取得 Amazon SES SMTP 憑證](smtp-credentials.md) 中的程序來從 Amazon SES 主控台取得這些憑證。
**重要**  
您的 SMTP 登入資料與您的 AWS 存取金鑰 ID 和私密存取金鑰不同。請勿嘗試使用您的 AWS 登入資料來驗證 SMTP 端點的身分。如需憑證的詳細資訊，請參閱 [Amazon SES 憑證的類型](send-email-concepts-credentials.md)。

   1. 確認已選取 **TLS encryption (TLS 加密)**。

   1. 返回 **Delivery (交付)** 標籤。

   1. 選擇 **Outbound Connections (對外連線)**。

   1. 在 **Outbound Connections (對外連線)** 對話方塊中，確認連接埠為 25 或 587。

   1. 選擇 **Advanced (進階)**。

   1. 針對 **Smart host (智慧型主機)** 名稱，輸入您要使用的 Amazon SES 端點，例如 *email-smtp.us-west-2.amazonaws.com*。如需可使用 Amazon SES 之 AWS 區域 的端點 URLs 清單，請參閱《》中的 [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)*AWS 一般參考*。

   1.  返回伺服器管理員儀表板。

   1. 在伺服器管理員儀表板上，以滑鼠右鍵按一下 **SMTP Virtual Server \$11 (SMTP 虛擬伺服器 \$11)**，然後重新啟動服務以採用新的組態。

   1. 透過此伺服器傳送一封電子郵件。您可以檢查訊息標題來確認是透過 Amazon SES 傳遞。

# 使用命令列測試 Amazon SES SMTP 界面的連線
<a name="send-email-smtp-client-command-line"></a>

您可從命令列使用本節所述的方法測試 Amazon SES SMTP 端點的連線、驗證 SMTP 憑證，以及針對連線問題進行故障診斷。這些程序使用大多數常見作業系統隨附的工具和程式庫。

如需 SMTP 連線問題的其他故障診斷相關資訊，請參閱 [Amazon SES SMTP 問題](troubleshoot-smtp.md)。

## 先決條件
<a name="send-email-smtp-client-command-line-prereqs"></a>

當您連線到 Amazon SES SMTP 界面時，您必須提供一組 SMTP 憑證。這些 SMTP 登入資料與您的標準 AWS 登入資料不同。這兩種憑證類型不可互換。如需如何取得 SMTP 憑證的更多相關資訊，請參閱 [取得 Amazon SES SMTP 憑證](smtp-credentials.md)。

## 測試您與 Amazon SES SMTP 界面的連線
<a name="send-email-smtp-client-command-line-testing"></a>

您可以使用命令列測試您與 Amazon SES SMTP 界面的連線，無需驗證或傳送任何訊息。此程序有助於對基本連線問題進行疑難排解。如果測試連線失敗，請參閱 [SMTP 問題](troubleshoot-smtp.md)。

本節包含使用 OpenSSL (包含大多數 Linux、macOS 和 Unix 發行版本，也適用於 Windows) 和 PowerShell (最新版 Windows 隨附) 中的 `Test-NetConnection` cmdlet，測試您的連線的程序。

------
#### [ Linux, macOS, or Unix ]

有兩種方式可以使用 OpenSSL 來連接到 Amazon SES SMTP 界面，透過連接埠 587 使用明確 SSL，或透過連接埠 465 使用隱含 SSL。

**使用明確 SSL 連接到 SMTP 界面**
+ 在命令列上，輸入下列命令來連接到 Amazon SES SMTP 伺服器：

  ```
  openssl s_client -crlf -quiet -starttls smtp -connect email-smtp.us-west-2.amazonaws.com:587
  ```

  在上述命令中，將 *email-smtp.us-west-2.amazonaws.com* 取代為您 AWS 區域的 Amazon SES SMTP 端點 URL。如需詳細資訊，請參閱[區域和 Amazon SES](regions.md)。

  若連線成功，您會看到類似以下的輸出：

  ```
  depth=2 C = US, O = Amazon, CN = Amazon Root CA 1
  verify return:1
  depth=1 C = US, O = Amazon, OU = Server CA 1B, CN = Amazon
  verify return:1
  depth=0 CN = email-smtp.us-west-2.amazonaws.com
  verify return:1
  250 Ok
  ```

  閒置 10 秒後連線將自動關閉。

或者，您可以使用 Implicit SSL (隱含 SSL) 透過連接埠 465 連接到 SMTP 界面。

**使用隱含 SSL 連接到 SMTP 界面**
+ 在命令列上，輸入下列命令來連接到 Amazon SES SMTP 伺服器：

  ```
  openssl s_client -crlf -quiet -connect email-smtp.us-west-2.amazonaws.com:465
  ```

  在上述命令中，將 *email-smtp.us-west-2.amazonaws.com* 取代為您 AWS 區域的 Amazon SES SMTP 端點 URL。如需詳細資訊，請參閱[區域和 Amazon SES](regions.md)。

  若連線成功，您會看到類似以下的輸出：

  ```
  depth=2 C = US, O = Amazon, CN = Amazon Root CA 1
  verify return:1
  depth=1 C = US, O = Amazon, OU = Server CA 1B, CN = Amazon
  verify return:1
  depth=0 CN = email-smtp.us-west-2.amazonaws.com
  verify return:1
  220 email-smtp.amazonaws.com ESMTP SimpleEmailService-d-VCSHDP1YZ A1b2C3d4E5f6G7h8I9j0
  ```

  閒置 10 秒後連線將自動關閉。

------
#### [ PowerShell ]

您可以在 PowerShell 中使用 [Test-NetConnection](https://docs.microsoft.com/en-us/powershell/module/nettcpip/test-netconnection) Cmdlet 來連線到 Amazon SES SMTP 伺服器。

**注意**  
`Test-NetConnection` Cmdlet 可判斷您的電腦是否能連接到 Amazon SES SMTP 端點。不過，它不會測試您的電腦是否能對 SMTP 端點建立隱含或明確的 SSL 連線。若要測試 SSL 連線，您可以安裝適用於 Windows 的 OpenSSL 以傳送測試電子郵件。

**使用 `Test-NetConnection` Cmdlet 連接到 SMTP 界面**
+ 在 PowerShell 中，輸入下列命令來連接到 Amazon SES SMTP 伺服器：

  ```
  Test-NetConnection -Port 587 -ComputerName email-smtp.us-west-2.amazonaws.com
  ```

  在上述命令中，將 *email-smtp.us-west-2.amazonaws.com* 取代為您 AWS 區域的 Amazon SES SMTP 端點 URL，並將 *587* 取代為連接埠號碼。如需 Amazon SES 中區域端點的詳細資訊，請參閱 [區域和 Amazon SES](regions.md)。

  如果連線成功，您會看到類似以下範例的輸出：

  ```
  ComputerName     : email-smtp.us-west-2.amazonaws.com
  RemoteAddress    : 198.51.100.126
  RemotePort       : 587
  InterfaceAlias   : Ethernet
  SourceAddress    : 203.0.113.46
  TcpTestSucceeded : True
  ```

------

## 使用命令列來透過 Amazon SES SMTP 界面傳送電子郵件
<a name="send-email-using-openssl"></a>

您也可以使用命令列來透過 Amazon SES SMTP 界面傳送訊息。此程序適用於測試 SMTP 憑證，以及測試特定收件人是否能夠接收您使用 Amazon SES 傳送的訊息。

------
#### [ Linux, macOS, or Unix ]

當電子郵件寄件者連接到 SMTP 伺服器時，用戶端將發出一組標準請求，而伺服器將以標準回應來回覆各項請求。這一系列的請求和回應稱為 *SMTP 對話*。使用 OpenSSL 連接到 Amazon SES SMTP 伺服器時，伺服器預期會發生 SMTP 對話。

當您計劃使用 OpenSSL 連接到 SMTP 界面時，則必須使用 base64 編碼來編碼您的 SMTP 登入資料。本節包含使用 base64 為您的登入資料進行編碼的程序。

**若要使用 SMTP 界面來自命令列傳送電子郵件**

1. 在命令列輸入以下內容，並將 *email-smtp.us-west-2.amazonaws.com* 取代為 Amazon SES SMTP 端點的 URL AWS 區域。如需詳細資訊，請參閱 [區域和 Amazon SES](regions.md)。：

   ```
    1. #!/bin/bash
    2. 
    3. # Prompt user to provide following information
    4. read -p "Configuration set: " CONFIGSET
    5. read -p "Enter SMTP username: " SMTPUsername
    6. read -p "Enter SMTP password: " SMTPPassword
    7. read -p "Sender email address: " MAILFROM
    8. read -p "Receiver email address: " RCPT
    9. read -p "Email subject: " SUBJECT
   10. read -p "Message to send: " DATA
   11. 
   12. echo
   13. 
   14. # Encode SMTP username and password using base64
   15. EncodedSMTPUsername=$(echo -n "$SMTPUsername" | openssl enc -base64)
   16. EncodedSMTPPassword=$(echo -n "$SMTPPassword" | openssl enc -base64)
   17. 
   18. # Construct the email
   19. Email="EHLO example.com
   20. AUTH LOGIN
   21. $EncodedSMTPUsername
   22. $EncodedSMTPPassword
   23. MAIL FROM: $MAILFROM
   24. RCPT TO: $RCPT
   25. DATA
   26. X-SES-CONFIGURATION-SET: $CONFIGSET
   27. From: $MAILFROM
   28. To: $RCPT
   29. Subject: $SUBJECT
   30. 
   31. $DATA
   32. .
   33. QUIT"
   34. 
   35. echo "$Email" | openssl s_client -crlf -quiet -starttls smtp -connect email-smtp.us-west-2.amazonaws.com:587
   ```

1. 在每個變數的提示中，輸入您的值。

1. 
   + 若要透過連接埠 465 使用隱含 SSL 傳送，請使用：

     ```
     openssl s_client -crlf -quiet -connect email-smtp.us-west-2.amazonaws.com:465
     ```

   如果 Amazon SES 已接受訊息，您會看到類似以下範例的輸出：

   ```
   250 Ok 01010160d7de98d8-21e57d9a-JZho-416c-bbe1-8ebaAexample-000000
   ```

   `250 Ok` 後方的數字與文字字串為電子郵件的訊息 ID。
**注意**  
閒置 10 秒後連線將自動關閉。

------
#### [ PowerShell ]

您可以使用 [Net.Mail.SmtpClient](https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=netframework-4.8) 類別，透過連接埠 587 使用明確 SSL 來傳送電子郵件。

**注意**  
`Net.Mail.SmtpClient` 類別已正式淘汰，且 Microsoft 建議您使用第三方程式庫。此程式碼僅供測試使用，不應用於生產環境工作負載。

**使用明確 SSL 透過 PowerShell 傳送電子郵件**

1. 在文字編輯器中，建立新檔案。將以下程式碼貼到檔案：

   ```
   function SendEmail($Server, $Port, $Sender, $Recipient, $Subject, $Body) {
       $Credentials = [Net.NetworkCredential](Get-Credential)
   
       $SMTPClient = New-Object Net.Mail.SmtpClient($Server, $Port)
       $SMTPClient.EnableSsl = $true
       $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Credentials.Username, $Credentials.Password);
   
       try {
           Write-Output "Sending message..."
           $SMTPClient.Send($Sender, $Recipient, $Subject, $Body)
           Write-Output "Message successfully sent to $($Recipient)"
       } catch [System.Exception] {
           Write-Output "An error occurred:"
           Write-Error $_
       }
   }
   
   function SendTestEmail(){
       $Server = "email-smtp.us-west-2.amazonaws.com"
       $Port = 587
   
       $Subject = "Test email sent from Amazon SES"
       $Body = "This message was sent from Amazon SES using PowerShell (explicit SSL, port 587)."
   
       $Sender = "sender@example.com"
       $Recipient = "recipient@example.com"
   
       SendEmail $Server $Port $Sender $Recipient $Subject $Body
   }
   
   SendTestEmail
   ```

   完成後，請將檔案儲存為 `SendEmail.ps1`。

1. 對您在前述步驟中建立的檔案進行下列變更：
   + 將 *sender@example.com* 替換為您想要傳送郵件的電子郵件地址。
   + 將 *recipient@example.com* 替換為您想要傳送郵件的電子郵件地址。
   + 以您 AWS 區域的 Amazon SES SMTP 端點 URL 取代 *email-smtp.us-west-2.amazonaws.com*。如需詳細資訊，請參閱[區域和 Amazon SES](regions.md)。

1. 在 PowerShell 中，輸入下列命令：

   ```
   .\path\to\SendEmail.ps1
   ```

   在上述命令中，將 *path\$1to\$1SendEmail.ps1* 取代為您在步驟 1 中建立的檔案路徑。

1. 出現提示時，請輸入您的 SMTP 使用者名稱和密碼。

或者，您也可以使用 [System.Web.Mail.SmtpMail](https://docs.microsoft.com/en-us/dotnet/api/system.web.mail.smtpmail?view=netframework-4.8) 類別，透過連接埠 465 使用隱含 SSL 來傳送電子郵件。

**注意**  
`System.Web.Mail.SmtpMail` 類別已正式淘汰，且 Microsoft 建議您使用第三方程式庫。此程式碼僅供測試使用，不應用於生產環境工作負載。

**使用隱含 SSL 透過 PowerShell 傳送電子郵件**

1. 在文字編輯器中，建立新檔案。將以下程式碼貼到檔案：

   ```
   [System.Reflection.Assembly]::LoadWithPartialName("System.Web") > $null
   
   function SendEmail($Server, $Port, $Sender, $Recipient, $Subject, $Body) {
       $Credentials = [Net.NetworkCredential](Get-Credential)
   
       $mail = New-Object System.Web.Mail.MailMessage
       $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", $Server)
       $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", $Port)
       $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", $true)
       $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", $Credentials.UserName)
       $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", $Credentials.Password)
       $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout", $timeout / 1000)
       $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2)
       $mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1)
   
       $mail.From = $Sender
       $mail.To = $Recipient
       $mail.Subject = $Subject
       $mail.Body = $Body
   
       try {
           Write-Output "Sending message..."
           [System.Web.Mail.SmtpMail]::Send($mail)
           Write-Output "Message successfully sent to $($Recipient)"
       } catch [System.Exception] {
           Write-Output "An error occurred:"
           Write-Error $_
       }
   }
   
   function SendTestEmail(){
       $Server = "email-smtp.us-west-2.amazonaws.com"
       $Port = 465
       
       $Subject = "Test email sent from Amazon SES"
       $Body = "This message was sent from Amazon SES using PowerShell (implicit SSL, port 465)."
   
       $Sender = "sender@example.com"
       $Recipient = "recipient@example.com"
   
       SendEmail $Server $Port $Sender $Recipient $Subject $Body
   }
   
   SendTestEmail
   ```

   完成後，請將檔案儲存為 `SendEmail.ps1`。

1. 對您在前述步驟中建立的檔案進行下列變更：
   + 將 *sender@example.com* 替換為您想要傳送郵件的電子郵件地址。
   + 將 *recipient@example.com* 替換為您想要傳送郵件的電子郵件地址。
   + 以您 AWS 區域的 Amazon SES SMTP 端點 URL 取代 *email-smtp.us-west-2.amazonaws.com*。如需詳細資訊，請參閱[區域和 Amazon SES](regions.md)。

1. 在 PowerShell 中，輸入下列命令：

   ```
   .\path\to\SendEmail.ps1
   ```

   在上述命令中，將 *path\$1to\$1SendEmail.ps1* 取代為您在步驟 1 中建立的檔案路徑。

1. 出現提示時，請輸入您的 SMTP 使用者名稱和密碼。

------

# 使用 Amazon SES API 來傳送電子郵件
<a name="send-email-api"></a>

若要透過 Amazon SES 傳送生產電子郵件，您可以使用簡易郵件傳輸協定 (SMTP) 界面或 Amazon SES API。如需 SMTP 界面的詳細資訊，請參閱 [使用 Amazon SES SMTP 界面來傳送電子郵件](send-email-smtp.md)。本節說明如何使用 API 傳送電子郵件。

使用 Amazon SES API 傳送電子郵件時，您可以指定訊息的內容，Amazon SES 會為您組合 MIME 電子郵件。或者，您也可以自行組合電子郵件，以便完全控制郵件內容。如需有關 API 的詳細資訊，請參閱 [Amazon Simple Email Service API 參考資料](https://docs.aws.amazon.com/ses/latest/APIReference/)。如需可使用 Amazon SES 之 AWS 區域 的端點 URLs 清單，請參閱《》中的 [Amazon Simple Email Service 端點和配額](https://docs.aws.amazon.com/general/latest/gr/ses.html)*AWS 一般參考*。

您可以透過下列方式呼叫 API：
+ **提出直接 HTTPS 請求 -** 這是最進階的方法，因為您必須手動處理驗證和簽章請求，然後手動建構請求。如需 Amazon SES API 的詳細資訊，請參閱 *API 第 2 版參考*中的[歡迎](https://docs.aws.amazon.com/ses/latest/APIReference-V2/Welcome.html)頁面。
+ **使用 AWS SDK -**AWS SDKs可讓您輕鬆存取多種 AWS 服務的 APIs，包括 Amazon SES。當您使用軟體開發套件時，它會負責身分驗證、請求簽署、重試邏輯、錯誤處理和其他低層級功能，讓您可以專注於建置令客戶滿意的應用程式。
+ **使用命令列界面 -** [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 為用於 Amazon SES 的命令列工具。我們也為在 PowerShell 環境中編寫指令碼的使用者提供[適用於 PowerShell 的AWS 工具](https://aws.amazon.com/powershell/)。

無論您直接或間接透過 AWS SDK、 AWS Command Line Interface 或 AWS Tools for PowerShell 存取 Amazon SES API，Amazon SES API 都會提供兩種不同的方式來傳送電子郵件，取決於您希望對電子郵件訊息合成的控制程度：
+ **格式化 -** Amazon SES 撰寫並傳送一封格式正確的電子郵件訊息。您只需提供「寄件者」和「收件人」地址、主旨與訊息內文。Amazon SES 就會完成其餘的工作。如需詳細資訊，請參閱「[使用 Amazon SES API 傳送格式化電子郵件](send-email-formatted.md)」。
+ **原始碼** - 您可以手動撰寫並傳送電子郵件訊息，指定您自訂的電子郵件標題及 MIME 類型。如果您有編排電子郵件格式的經驗、原始碼界面可讓您擁有更多訊息編寫控制權。如需詳細資訊，請參閱[使用 Amazon SES API v2 傳送原始電子郵件](send-email-raw.md)。

**Topics**
+ [使用 Amazon SES API 傳送格式化電子郵件](send-email-formatted.md)
+ [使用 Amazon SES API v2 傳送原始電子郵件](send-email-raw.md)
+ [使用範本透過 Amazon SES API 傳送個人化電子郵件](send-personalized-email-api.md)
+ [使用 AWS SDK 透過 Amazon SES 傳送電子郵件](send-an-email-using-sdk-programmatically.md)
+ [Amazon SES 支援的內容編碼](content-encodings.md)

# 使用 Amazon SES API 傳送格式化電子郵件
<a name="send-email-formatted"></a>

您可以使用 傳送格式化的電子郵件， AWS 管理主控台 或透過應用程式直接呼叫 Amazon SES API，或透過 AWS SDK AWS Command Line Interface、 或 間接呼叫 AWS Tools for Windows PowerShell。

Amazon SES API 提供 `SendEmail` 動作，可讓您撰寫並傳送格式化的電子郵件。`SendEmail` 需要「寄件者」地址、「收件人」地址、郵件主旨和郵件內文 (文字、HTML 或同時使用)。如需詳細資訊，請參閱 [SendEmail](https://docs.aws.amazon.com/ses/latest/APIReference/API_SendEmail.html) (API 參考) 或 [SendEmail](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html) (API 第 2 版參考)。

**注意**  
電子郵件地址必須為 7 位元 ASCII 字串。如果您要寄出的電子郵件地址或收件人的電子郵件地址網域部分包含 Unicode 字元，您必須使用 Punycode 編碼來將網域編碼。如需詳細資訊，請參閱 [RFC 3492](https://tools.ietf.org/html/rfc3492)。

如需使用各種程式設計語言撰寫格式化訊息的範例，請參閱 [程式碼範例](send-an-email-using-sdk-programmatically.md#send-an-email-using-sdk-programmatically-examples)。

如需對 `SendEmail` 執行多重呼叫時提高電子郵件傳送速率的方法，請參閱 [透過 Amazon SES 增加輸送量](troubleshoot-throughput-problems.md)。

# 使用 Amazon SES API v2 傳送原始電子郵件
<a name="send-email-raw"></a>

您可以使用 Amazon SES API v2 `SendEmail`操作搭配指定的內容類型`raw`，使用原始電子郵件格式將自訂訊息傳送給收件人。

## 關於電子郵件標頭欄位
<a name="send-email-raw-headers"></a>

簡易郵件傳輸協定 (SMTP) 透過定義郵件信封與其中部分參數來指定傳送電子郵件訊息的方式，但是不會與訊息內容產生關連。反之，網際網路訊息格式 ([RFC 5322](https://www.ietf.org/rfc/rfc5322.txt)) 則會定義建構訊息的方法。

在網際網路訊息格式的明確定義下，每個電子郵件訊息都會含有標題和內文。標題包含訊息中繼資料，而內文則包含訊息本身。如需有關電子郵件標題和內文的詳細資訊，請參閱 [Amazon SES 中的電子郵件格式](send-email-concepts-email-format.md)。

## 使用原始電子郵件 MIME 訊息建構
<a name="send-email-raw-mime"></a>

SMTP 協定原先旨在傳送只包含 7 位元 ASCII 字元的電子郵件訊息。此規範使得 SMTP 不足以因應非 ASCII 文字編碼 (如 Unicode)、二進位內容或附件。開發多用途網際網路郵件延伸標準 (MIME) 的目的在於，能夠使用 SMTP 來傳送許多其他類型的內容。

MIME 標準的運作方式是將訊息內文分成多個部分，然後指定每個部分所要執行的動作。例如，電子郵件訊息內文的一部分可能是純文字，而另一部分可能使用 HTML。此外，MIME 允許電子郵件訊息包含一或多個附件。訊息收件人可以在自己的電子郵件用戶端中檢視附件，也可以儲存附件。

訊息標題和內容則是以空白行分隔。每個部分的電子郵件則是以邊界為分隔，邊界為字元字串，用以標記出每個部分的開始與結束。

以下範例中的分段訊息包含文字和 HTML 部分，以及附件。附件應該放在[附件標題](#send-email-mime-encoding-files)的正下方，並且通常以 `base64` 編碼，如此範例所示。

```
 1. From: "Sender Name" <sender@example.com>
 2. To: recipient@example.com
 3. Subject: Customer service contact info
 4. Content-Type: multipart/mixed;
 5.     boundary="a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a"
 6. 
 7. --a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a
 8. Content-Type: multipart/alternative;
 9.     boundary="sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a"
10. 
11. --sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a
12. Content-Type: text/plain; charset=iso-8859-1
13. Content-Transfer-Encoding: quoted-printable
14. 
15. Please see the attached file for a list of customers to contact.
16. 
17. --sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a
18. Content-Type: text/html; charset=iso-8859-1
19. Content-Transfer-Encoding: quoted-printable
20. 
21. <html>
22. <head></head>
23. <body>
24. <h1>Hello!</h1>
25. <p>Please see the attached file for a list of customers to contact.</p>
26. </body>
27. </html>
28. 
29. --sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a--
30. 
31. --a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a
32. Content-Type: text/plain; name="customers.txt"
33. Content-Description: customers.txt
34. Content-Disposition: attachment;filename="customers.txt";
35.     creation-date="Sat, 05 Aug 2017 19:35:36 GMT";
36. Content-Transfer-Encoding: base64
37. 
38. SUQsRmlyc3ROYW1lLExhc3ROYW1lLENvdW50cnkKMzQ4LEpvaG4sU3RpbGVzLENhbmFkYQo5MjM4
39. OSxKaWUsTGl1LENoaW5hCjczNCxTaGlybGV5LFJvZHJpZ3VleixVbml0ZWQgU3RhdGVzCjI4OTMs
40. QW5heWEsSXllbmdhcixJbmRpYQ==
41. 
42. --a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a--
```

訊息的內容類型為 `multipart/mixed`，這表示訊息有許多部分 (在這個範例中，分為內文與附件)，而接收用戶端必須單獨處理每個部分。

內文部分中的內嵌是使用 `multipart/alternative` 內容類型的第二個部分。此內容類型表示每個部分皆包含相同內容的不同版本 (在此範例中，包含文字版本與 HTML 版本)。如果收件人的電子郵件用戶端可以顯示 HTML 內容，則會顯示訊息內文的 HTML 版本。如果收件人的電子郵件用戶端無法顯示 HTML 內容，則會顯示訊息內文的純文字版本。

這兩種訊息版本也都包含附件 (在本案例中是包含部分客戶名稱的簡短文字檔案)。

當您將 MIME 部分如此範例所示內嵌於另一部分時，在內嵌部分必須使用與原生部分的 `boundary` 參數不同的 `boundary` 參數。這些邊界應為獨特的字元字串。若要各個 MIME 部分間的邊界，請輸入兩個 (--)，接著輸入邊界字串。在每個 MIME 部分的結尾處，分別在邊界字串的開頭和結尾放上兩個連字號。

**注意**  
訊息不能包含超過 500 個 MIME 部分。

### MIME 編碼
<a name="send-email-mime-encoding"></a>

為維持與舊版系統的相容性，Amazon SES 接受 [RFC 2821](https://tools.ietf.org/html/rfc2821) 所定義 SMTP 的 7 位元 ASCII 限制。如果您想要傳送包含非 ASCII 字元的內容，您必須將這些字元編碼成使用 7 位元 ASCII 字元的格式。

#### 電子郵件位址
<a name="send-email-mime-encoding-addresses"></a>

電子郵件地址必須為 7 位元 ASCII 字串。如果您要寄出的電子郵件地址或收件人的電子郵件地址網域部分包含 Unicode 字元，您必須使用 Punycode 編碼來將網域編碼。Punycode 不可用於電子郵件的本機部分 (也就是 @ 前的部分)，也不能使用於「友善寄件人」名稱中。如果您想要在「易記」名稱中使用 Unicode 字元，您必須使用 MIME 編碼詞語法來編碼「易記」名稱，如本節所述。如需 Punycode 的詳細資訊，請參閱 [RFC 3492](http://tools.ietf.org/html/rfc3492)。

**注意**  
此規則僅適用於您在訊息信封中指定的電子郵件地址，不適用於訊息標頭。當您使用 Amazon SES API v2 `SendEmail`操作時，您在 `Source`和 `Destinations` 參數中指定的地址會分別定義信封寄件者和收件人。

#### 電子郵件標頭
<a name="send-email-mime-encoding-headers"></a>

若要編碼訊息標頭，請使用 MIME 編碼的字詞語法。MIME 編碼的字詞語法使用以下格式：

```
=?charset?encoding?encoded-text?=
```

`encoding` 的值可以是 `Q` 或 `B`。如果編碼值為 `Q`，則值 `encoded-text` 必須使用 Q 編碼。如果編碼值為 `B`，則值 `encoded-text` 必須使用 base64 編碼。

例如，如果您想要在電子郵件主旨列中使用字串「Як ти поживаєш?」，您可以使用下列其中一種編碼：
+ **Q 編碼**

  ```
  =?utf-8?Q?=D0=AF=D0=BA_=D1=82=D0=B8_=D0=BF=D0=BE=D0=B6=D0=B8=D0=B2=D0=B0=D1=94=D1=88=3F?=
  ```
+ **Base64 編碼**

  ```
  =?utf-8?B?0K/QuiDRgtC4INC/0L7QttC40LLQsNGU0Yg/?=
  ```

如需 Q 編碼的詳細資訊，請參閱 [RFC 2047](https://tools.ietf.org/html/rfc2047)。如需 base64 編碼的詳細資訊，請參閱 [RFC 2045](https://tools.ietf.org/html/rfc2045)。

#### 訊息內文
<a name="send-email-mime-encoding-body"></a>

若要編碼訊息的內文，您可以使用 quoted-printable 編碼或 base64 編碼。然後，使用 `Content-Transfer-Encoding` 標頭，指出您使用的編碼方案。

例如，假設您的訊息內文包含下列文字：

१९७२ मे रे टॉमलिंसन ने पहला ई-मेल संदेश भेजा \$1 रे टॉमलिंसन ने ही सर्वप्रथम @ चिन्ह का चयन किया और इन्ही को ईमेल का आविष्कारक माना जाता है

如果您選擇使用 base64 編碼編碼此段文字，請先指定以下標頭：

```
Content-Transfer-Encoding: base64
```

然後，在電子郵件的內文區段，包含 base64 編碼的文字：

```
4KWn4KWv4KWt4KWoIOCkruClhyDgpLDgpYcg4KSf4KWJ4KSu4KSy4KS/4KSC4KS44KSoIOCkqOCl
hyDgpKrgpLngpLLgpL4g4KSILeCkruClh+CksiDgpLjgpILgpKbgpYfgpLYg4KSt4KWH4KSc4KS+
IHwg4KSw4KWHIOCkn+ClieCkruCksuCkv+CkguCkuOCkqCDgpKjgpYcg4KS54KWAIOCkuOCksOCl
jeCkteCkquCljeCksOCkpeCkriBAIOCkmuCkv+CkqOCljeCkuSDgpJXgpL4g4KSa4KSv4KSoIOCk
leCkv+Ckr+CkviDgpJTgpLAg4KSH4KSo4KWN4KS54KWAIOCkleCliyDgpIjgpK7gpYfgpLIg4KSV
4KS+IOCkhuCkteCkv+Ckt+CljeCkleCkvuCksOCklSDgpK7gpL7gpKjgpL4g4KSc4KS+4KSk4KS+
IOCkueCliAo=
```

**注意**  
在某些情況下，您可以在透過 Amazon SES 傳送的訊息中使用 8 位元 `Content-Transfer-Encoding`。不過，如果 Amazon SES 必須變更您的訊息 (例如當您使用[開啟與點選追蹤](faqs-metrics.md)時)，訊息送達收件人信箱時，可能無法正確顯示 8 位元編碼的內容。因此，您應該一律編碼非 7 位元 ASCII 的內容。

#### 檔案附件
<a name="send-email-mime-encoding-files"></a>

若要將檔案附加到電子郵件，您必須使用 base64 編碼來編碼附件。附件通常會放在專用的 MIME 訊息部分，包含下列標頭：
+ **Content-Type** - 附件的檔案類型。以下是常見的 MIME 內容類型宣告範例：
  + **純文字檔案** - `Content-Type: text/plain; name="sample.txt"`
  + **Microsoft Word 文件** - `Content-Type: application/msword; name="document.docx"`
  + **JPG 映像** - `Content-Type: image/jpeg; name="photo.jpeg"`
+ **Content-Disposition** - 指定收件人的電子郵件用戶端應該如何處理內容。針對附件，此值為 `Content-Disposition: attachment`。
+ **Content-Transfer-Encoding** - 過去用來編碼附件的方案。針對檔案附件，此幾乎一律為 `base64`。
+ **編碼附件** - 您必須對實際附件進行編碼，并將其包含在附件標題下方的正文中，[如範例中所示](#send-email-raw-mime)。

Amazon SES 接受最常見的檔案類型。如需 Amazon SES 不接受的檔案類型清單，請參閱「[SES 不支援的附件類型](attachments.md#mime-types)」。

## 使用 Amazon SES API v2 傳送原始電子郵件
<a name="send-email-raw-api"></a>

Amazon SES API v2 提供 `SendEmail`動作，可讓您以設定內容類型為簡單、原始或範本時指定的格式撰寫和傳送電子郵件訊息。如需完整說明，請參閱 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html)。下列範例會將內容類型指定為 `raw`，以使用原始電子郵件格式傳送訊息。

**注意**  
如需對 `SendEmail` 執行多重呼叫時提高電子郵件傳送速率的方法，請參閱 [透過 Amazon SES 增加輸送量](troubleshoot-throughput-problems.md)。

訊息內文必須包含一封格式正確的電子郵件原始碼訊息，並使用適當的標題欄位與訊息內文編碼。雖然您可以在應用程式內手動建構訊息原始碼，但是使用現有的郵件程式庫來操作會更簡單。

------
#### [ Java ]

以下程式碼範例說明如何使用 [JavaMail](https://javaee.github.io/javamail/) 程式庫和 [適用於 Java 的 AWS SDK](https://aws.amazon.com/sdk-for-java) 來撰寫與傳送電子郵件原始碼。

```
  1. package com.amazonaws.samples;
  2. 
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.io.PrintStream;
  6. import java.nio.ByteBuffer;
  7. import java.util.Properties;
  8. 
  9. // JavaMail libraries. Download the JavaMail API 
 10. // from https://javaee.github.io/javamail/
 11. import javax.activation.DataHandler;
 12. import javax.activation.DataSource;
 13. import javax.activation.FileDataSource;
 14. import javax.mail.Message;
 15. import javax.mail.MessagingException;
 16. import javax.mail.Session;
 17. import javax.mail.internet.AddressException;
 18. import javax.mail.internet.InternetAddress;
 19. import javax.mail.internet.MimeBodyPart;
 20. import javax.mail.internet.MimeMessage;
 21. import javax.mail.internet.MimeMultipart;
 22. 
 23. // AWS SDK libraries. Download the 適用於 Java 的 AWS SDK // from https://aws.amazon.com/sdk-for-java
 24. import com.amazonaws.regions.Regions;
 25. import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
 26. import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
 27. import com.amazonaws.services.simpleemail.model.RawMessage;
 28. import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
 29. 
 30. public class AmazonSESSample {
 31. 
 32. 	// Replace sender@example.com with your "From" address.
 33. 	// This address must be verified with Amazon SES.
 34. 	private static String SENDER = "Sender Name <sender@example.com>";
 35. 
 36. 	// Replace recipient@example.com with a "To" address. If your account 
 37. 	// is still in the sandbox, this address must be verified.
 38. 	private static String RECIPIENT = "recipient@example.com";
 39. 
 40. 	// Specify a configuration set. If you do not want to use a configuration
 41. 	// set, comment the following variable, and the 
 42. 	// ConfigurationSetName=CONFIGURATION_SET argument below.
 43. 	private static String CONFIGURATION_SET = "ConfigSet";
 44. 
 45. 	// The subject line for the email.
 46. 	private static String SUBJECT = "Customer service contact info";
 47. 
 48. 	// The full path to the file that will be attached to the email.
 49. 	// If you're using Windows, escape backslashes as shown in this variable.
 50. 	private static String ATTACHMENT = "C:\\Users\\sender\\customers-to-contact.xlsx";
 51. 
 52. 	// The email body for recipients with non-HTML email clients.
 53. 	private static String BODY_TEXT = "Hello,\r\n"
 54.                                         + "Please see the attached file for a list "
 55.                                         + "of customers to contact.";
 56. 
 57. 	// The HTML body of the email.
 58. 	private static String BODY_HTML = "<html>"
 59.                                         + "<head></head>"
 60.                                         + "<body>"
 61.                                         + "<h1>Hello!</h1>"
 62.                                         + "<p>Please see the attached file for a "
 63.                                         + "list of customers to contact.</p>"
 64.                                         + "</body>"
 65.                                         + "</html>";
 66. 
 67.     public static void main(String[] args) throws AddressException, MessagingException, IOException {
 68.             	
 69.     	Session session = Session.getDefaultInstance(new Properties());
 70.         
 71.         // Create a new MimeMessage object.
 72.         MimeMessage message = new MimeMessage(session);
 73.         
 74.         // Add subject, from and to lines.
 75.         message.setSubject(SUBJECT, "UTF-8");
 76.         message.setFrom(new InternetAddress(SENDER));
 77.         message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));
 78. 
 79.         // Create a multipart/alternative child container.
 80.         MimeMultipart msg_body = new MimeMultipart("alternative");
 81.         
 82.         // Create a wrapper for the HTML and text parts.        
 83.         MimeBodyPart wrap = new MimeBodyPart();
 84.         
 85.         // Define the text part.
 86.         MimeBodyPart textPart = new MimeBodyPart();
 87.         textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
 88.                 
 89.         // Define the HTML part.
 90.         MimeBodyPart htmlPart = new MimeBodyPart();
 91.         htmlPart.setContent(BODY_HTML,"text/html; charset=UTF-8");
 92.                 
 93.         // Add the text and HTML parts to the child container.
 94.         msg_body.addBodyPart(textPart);
 95.         msg_body.addBodyPart(htmlPart);
 96.         
 97.         // Add the child container to the wrapper object.
 98.         wrap.setContent(msg_body);
 99.         
100.         // Create a multipart/mixed parent container.
101.         MimeMultipart msg = new MimeMultipart("mixed");
102.         
103.         // Add the parent container to the message.
104.         message.setContent(msg);
105.         
106.         // Add the multipart/alternative part to the message.
107.         msg.addBodyPart(wrap);
108.         
109.         // Define the attachment
110.         MimeBodyPart att = new MimeBodyPart();
111.         DataSource fds = new FileDataSource(ATTACHMENT);
112.         att.setDataHandler(new DataHandler(fds));
113.         att.setFileName(fds.getName());
114.         
115.         // Add the attachment to the message.
116.         msg.addBodyPart(att);
117. 
118.         // Try to send the email.
119.         try {
120.             System.out.println("Attempting to send an email through Amazon SES "
121.                               +"using the AWS SDK for Java...");
122. 
123.             // Instantiate an Amazon SES client, which will make the service 
124.             // call with the supplied AWS credentials.
125.             AmazonSimpleEmailService client = 
126.                     AmazonSimpleEmailServiceClientBuilder.standard()
127.                     // Replace US_WEST_2 with the AWS Region you're using for
128.                     // Amazon SES.
129.                     .withRegion(Regions.US_WEST_2).build();
130.             
131.             // Print the raw email content on the console
132.             PrintStream out = System.out;
133.             message.writeTo(out);
134. 
135.             // Send the email.
136.             ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
137.             message.writeTo(outputStream);
138.             RawMessage rawMessage = 
139.             		new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
140. 
141.             SendRawEmailRequest rawEmailRequest = 
142.             		new SendRawEmailRequest(rawMessage)
143.             		    .withConfigurationSetName(CONFIGURATION_SET);
144.             
145.             client.sendRawEmail(rawEmailRequest);
146.             System.out.println("Email sent!");
147.         // Display an error if something goes wrong.
148.         } catch (Exception ex) {
149.           System.out.println("Email Failed");
150.             System.err.println("Error message: " + ex.getMessage());
151.             ex.printStackTrace();
152.         }
153.     }
154. }
```

------
#### [ Python ]

以下程式碼範例說明如何使用 [Python email.mime](https://docs.python.org/3.8/library/email.mime.html) 套件和 [適用於 Python (Boto) 的 AWS SDK](https://aws.amazon.com/sdk-for-python) 來撰寫與傳送電子郵件原始碼。

```
 1. import json
 2. import boto3
 3. from botocore.exceptions import ClientError
 4. from email.mime.multipart import MIMEMultipart
 5. from email.mime.text import MIMEText
 6. from email.mime.application import MIMEApplication
 7. import os
 8. 
 9. def boto3_rawemailv2():
10.     SENDER = "Sender <sender@example.com>"
11.     RECIPIENT = "recipient@example.com"
12.     CONFIGURATION_SET = "ConfigSet"
13.     AWS_REGION = "us-east-1"
14.     SUBJECT = "Customer service contact info"
15.     ATTACHMENT = "path/to/customers-to-contact.xlsx"
16.     BODY_TEXT = "Hello,\r\nPlease see the attached file for a list of customers to contact."
17. 
18.     # The HTML body of the email.
19.     BODY_HTML = """\
20.     <html>
21.     <head/>
22.     <body>
23.     <h1>Hello!</h1>
24.     <p>Please see the attached file for a list of customers to contact.</p>
25.     </body>
26.     </html>
27.     """
28. 
29.     # The character encoding for the email.
30.     CHARSET = "utf-8"
31.     msg = MIMEMultipart('mixed')
32.     # Add subject, from and to lines.
33.     msg['Subject'] = SUBJECT 
34.     msg['From'] = SENDER 
35.     msg['To'] = RECIPIENT
36.     
37.     # Create a multipart/alternative child container.
38.     msg_body = MIMEMultipart('alternative')
39.     
40.     # Encode the text and HTML content and set the character encoding. This step is
41.     # necessary if you're sending a message with characters outside the ASCII range.
42.     textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
43.     htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)
44.     
45.     # Add the text and HTML parts to the child container.
46.     msg_body.attach(textpart)
47.     msg_body.attach(htmlpart)
48.     
49.     # Define the attachment part and encode it using MIMEApplication.
50.     att = MIMEApplication(open(ATTACHMENT, 'rb').read())
51.     
52.     # Add a header to tell the email client to treat this part as an attachment,
53.     # and to give the attachment a name.
54.     att.add_header('Content-Disposition','attachment',filename=os.path.basename(ATTACHMENT))
55.     
56.     # Attach the multipart/alternative child container to the multipart/mixed
57.     # parent container.
58.     msg.attach(msg_body)
59.     msg.attach(att)
60. 
61.     #changes start from here
62.     strmsg = str(msg)
63.     body = bytes (strmsg, 'utf-8')
64. 
65. 
66. 
67.     
68.     client = boto3.client('sesv2')
69.     response = client.send_email(
70.     FromEmailAddress=SENDER,
71.     Destination={
72.         'ToAddresses': [RECIPIENT]
73.     },
74.     Content={
75.         'Raw': {
76.             'Data': body
77.         }
78.     }
79.     )
80.     print(response)
81. boto3_rawemailv2 ()
```

------

# 使用範本透過 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` 錯誤。

# 使用 AWS SDK 透過 Amazon SES 傳送電子郵件
<a name="send-an-email-using-sdk-programmatically"></a>

您可以使用 AWS SDK 透過 Amazon SES 傳送電子郵件。 AWS SDKs提供多種程式設計語言。如需詳細資訊，請參閱 [Amazon Web Services 適用工具](https://aws.amazon.com/tools/#sdk)。

## 先決條件
<a name="send-an-email-using-sdk-programmatically-prereqs"></a>

必須完成下列必要條件，才能完成下一節中的任何程式碼範例：
+ 完成 [設定 Amazon Simple Email Service](setting-up.md) 中的步驟 (如果您尚未這麼做)。
+ **以 Amazon SES 驗證您的電子郵件地址** - 您必須先驗證您為寄件者電子郵件地址的擁有者，才可以使用 Amazon SES 傳送電子郵件。如果您的帳戶仍在 Amazon SES 沙盒中，您必須同時驗證收件人地址。建議您使用 Amazon SES 主控台來驗證電子郵件地址。如需詳細資訊，請參閱[建立電子郵件地址身分](creating-identities.md#verify-email-addresses-procedure)。
+ **取得您的 AWS 登入**資料 - 您需要 AWS 存取金鑰 ID 和 AWS 私密存取金鑰，才能使用 SDK 存取 Amazon SES。您可以使用 AWS 管理主控台中的 [Security Credentials (安全憑證)](https://console.aws.amazon.com/iam/home?#security_credential) 頁面找到您的憑證。如需憑證的詳細資訊，請參閱 [Amazon SES 憑證的類型](send-email-concepts-credentials.md)。
+ **建立共用憑證檔案** - 為讓本節中的範本程式碼正常運作，須建立共用憑證檔案。如需詳細資訊，請參閱[建立共用登入資料檔案，以便在使用 AWS SDK 透過 Amazon SES 傳送電子郵件時使用](create-shared-credentials-file.md)。

## 程式碼範例
<a name="send-an-email-using-sdk-programmatically-examples"></a>

**重要**  
在如下教學課程中，可傳送電子郵件給自己，以確認是否成功收到。如需進一步試驗或負載測試，請使用 Amazon SES 信箱模擬器。傳送到信箱模擬器的電子郵件不會計入您的傳送份額或退信率與投訴率。如需詳細資訊，請參閱[手動使用信箱模擬器](send-an-email-from-console.md#send-email-simulator)。

**Topics**

------
#### [ .NET ]

下列程序說明如何使用 [Visual Studio](https://www.visualstudio.com/) 與 適用於 .NET 的 AWS SDK透過 Amazon SES 傳送電子郵件。

這個解決方案使用以下元件測試：
+ Microsoft Visual Studio Community 2017，15.4.0 版。
+ Microsoft .NET Framework 版本 4.6.1。
+ 使用 NuGet 安裝的 AWSSDK.Core 套件 (版本 3.3.19)。
+ 使用 NuGet 安裝的 AWSSDK.SimpleEmail 套件 (版本 3.3.6.1)。

**開始之前，請執行以下任務：**
+ **安裝 Visual Studio** - Visual Studio 可在 [https://www.visualstudio.com/](https://www.visualstudio.com/) 取得。

**使用 傳送電子郵件 適用於 .NET 的 AWS SDK**

1. 執行以下步驟以建立新專案：

   1. 啟動 Visual Studio。

   1. 在 **File (檔案)** 選單上，選擇 **New (新增)**、**Project (專案)**。

   1. 在 **New Project (新增專案)** 視窗上，於左側面板內，展開 **Installed (已安裝)**，然後展開 **Visual C\$1**。

   1. 在右側的面板上，選擇 **Console App (主控台應用程式) (.NET Framework)**。

   1. 針對 **Name (名稱)**，輸入 **AmazonSESSample**，然後選擇 **OK (確定)**。

1. 完成以下步驟，使用 NuGet 在您的解決方案納入 Amazon SES 套件：

   1. 在 **Solution Explorer (方案總管)** 窗格中，以滑鼠右鍵按一下專案，然後選擇 **Manage NuGet Packages (管理 NuGet 套件)**。

   1. 在 **NuGet: AmazonSESSample** 標籤上，選擇 **Browse (瀏覽)**。

   1. 在搜尋方塊中，輸入 **AWSSDK.SimpleEmail**。

   1. 選擇 **AWSSDK.SimpleEmail** 套件，然後選擇 **Install (安裝)**。

   1. 在 **Preview Changes (預覽變更)** 視窗上，選擇 **OK (確定)**。

1. 在 **Program.cs** 標籤上，貼上以下程式碼：

   ```
    1. using Amazon;
    2. using System;
    3. using System.Collections.Generic;
    4. using Amazon.SimpleEmail;
    5. using Amazon.SimpleEmail.Model;
    6. 
    7. namespace AmazonSESSample 
    8. {
    9.     class Program
   10.     {
   11.         // Replace sender@example.com with your "From" address.
   12.         // This address must be verified with Amazon SES.
   13.         static readonly string senderAddress = "sender@example.com";
   14. 
   15.         // Replace recipient@example.com with a "To" address. If your account
   16.         // is still in the sandbox, this address must be verified.
   17.         static readonly string receiverAddress = "recipient@example.com";
   18. 
   19.         // The configuration set to use for this email. If you do not want to use a
   20.         // configuration set, comment out the following property and the
   21.         // ConfigurationSetName = configSet argument below. 
   22.         static readonly string configSet = "ConfigSet";
   23. 
   24.         // The subject line for the email.
   25.         static readonly string subject = "Amazon SES test (適用於 .NET 的 AWS SDK)";
   26. 
   27.         // The email body for recipients with non-HTML email clients.
   28.         static readonly string textBody = "Amazon SES Test (.NET)\r\n" 
   29.                                         + "This email was sent through Amazon SES "
   30.                                         + "using the 適用於 .NET 的 AWS SDK.";
   31.         
   32.         // The HTML body of the email.
   33.         static readonly string htmlBody = @"<html>
   34. <head></head>
   35. <body>
   36.   <h1>Amazon SES Test (適用於 .NET 的 SDK)</h1>
   37.   <p>This email was sent with
   38.     <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the
   39.     <a href='https://aws.amazon.com/sdk-for-net/'> 適用於 .NET 的 AWS SDK</a>.</p>
   40. </body>
   41. </html>";
   42. 
   43.         static void Main(string[] args)
   44.         {
   45.             // Replace USWest2 with the AWS Region you're using for Amazon SES.
   46.             // Acceptable values are EUWest1, USEast1, and USWest2.
   47.             using (var client = new AmazonSimpleEmailServiceClient(RegionEndpoint.USWest2))
   48.             {
   49.                 var sendRequest = new SendEmailRequest
   50.                 {
   51.                     Source = senderAddress,
   52.                     Destination = new Destination
   53.                     {
   54.                         ToAddresses =
   55.                         new List<string> { receiverAddress }
   56.                     },
   57.                     Message = new Message
   58.                     {
   59.                         Subject = new Content(subject),
   60.                         Body = new Body
   61.                         {
   62.                             Html = new Content
   63.                             {
   64.                                 Charset = "UTF-8",
   65.                                 Data = htmlBody
   66.                             },
   67.                             Text = new Content
   68.                             {
   69.                                 Charset = "UTF-8",
   70.                                 Data = textBody
   71.                             }
   72.                         }
   73.                     },
   74.                     // If you are not using a configuration set, comment
   75.                     // or remove the following line 
   76.                     ConfigurationSetName = configSet
   77.                 };
   78.                 try
   79.                 {
   80.                     Console.WriteLine("Sending email using Amazon SES...");
   81.                     var response = client.SendEmail(sendRequest);
   82.                     Console.WriteLine("The email was sent successfully.");
   83.                 }
   84.                 catch (Exception ex)
   85.                 {
   86.                     Console.WriteLine("The email was not sent.");
   87.                     Console.WriteLine("Error message: " + ex.Message);
   88. 
   89.                 }
   90.             }
   91. 
   92.             Console.Write("Press any key to continue...");
   93.             Console.ReadKey();
   94.         }
   95.     }
   96. }
   ```

1. 在程式碼編輯器中，執行以下動作：
   + 以您的「寄件人」電子郵件地址取代 *sender@example.com*。此地址必須經過驗證。如需詳細資訊，請參閱「[在 Amazon SES 中驗證身分](verify-addresses-and-domains.md)」。
   + 以 "To:" 地址取代 *recipient@example.com*。若您的帳戶仍在沙盒中，您也必須驗證此地址。
   + 在傳送此電子郵件時使用您要使用的組態集名稱取代 *ConfigSet*。
   + 以您使用 Amazon SES 傳送電子郵件的 AWS 區域 端點名稱取代 *USWest2*。如需可使用 Amazon SES 的區域清單，請參閱 *AWS 一般參考* 中的 [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)。

   完成時，請儲存 `Program.cs`。

1. 完成以下步驟以建置並執行應用程式：

   1. 在 **Build (建置)** 選單上，選擇 **Build Solution (建置解決方案)**。

   1. 在 **Debug (偵錯)** 選單上，選擇 **Start Debugging (開始偵錯)**。將顯示主控台視窗。

1. 檢視主控台輸出。若電子郵件成功傳送，主控台將顯示 "`The email was sent successfully.`"

1. 如果電子郵件已成功傳送，請登入收件人地址的電子郵件用戶端。可以看到您已傳送的訊息。

------
#### [ Java ]

下列程序說明如何使用[適用於 Java EE 開發人員的 Eclipse IDE，](http://www.eclipse.org/)以及[AWS Toolkit for Eclipse](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)建立 AWS SDK 專案和修改 Java 程式碼，以透過 Amazon SES 傳送電子郵件。

**開始之前，請執行以下任務：**
+ **安裝 Eclipse** - Eclipse 可在 [https://www.eclipse.org/downloads](https://www.eclipse.org/downloads) 下載。此教學中的程式碼使用 Eclipse Neon.3 (版本 4.6.3) 及 Java Runtime Environment 執行版本 1.8 來完成測試。
+ **安裝 AWS Toolkit for Eclipse**- 將 AWS Toolkit for Eclipse 新增至 Eclipse 安裝的指示可在 https：//[https://aws.amazon.com/eclipse](https://aws.amazon.com/eclipse) 取得。此教學中的程式碼使用 AWS Toolkit for Eclipse版本 2.3.1 完成測試。

**使用 傳送電子郵件 適用於 Java 的 AWS SDK**

1. 透過執行下列步驟，在 Eclipse 中建立 AWS Java 專案：

   1. 啟動 Eclipse。

   1. 在 **File (檔案)** 選單上，選擇 **New (新增)**，再選擇 **Other (其他)**。在 **New (新增)** 視窗上，展開 **AWS** 資料夾，然後選擇 **AWS Java Project (AWS Java 專案)**。

   1. 在**新 AWS Java 專案**對話方塊中，執行下列動作：

      1. 針對 **Project name** (專案名稱)，輸入專案的名稱。

      1. 在**適用於 Java 的 AWS SDK 範例**底下，選取 **Amazon Simple Email Service JavaMail 範例**。

      1. 選擇**完成**。

1. 在 Eclipse 的 **Package Explorer** (套件瀏覽器) 窗格中，展開您的專案。

1. 在您的專案下，展開 `src/main/java` 資料夾、展開 `com.amazon.aws.samples` 資料夾，然後按兩下 `AmazonSESSample.java`。

1. 以下列程式碼取代 `AmazonSESSample.java` 所有內容：

   ```
    1. package com.amazonaws.samples;
    2. 
    3. import java.io.IOException;
    4. 
    5. import com.amazonaws.regions.Regions;
    6. import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
    7. import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
    8. import com.amazonaws.services.simpleemail.model.Body;
    9. import com.amazonaws.services.simpleemail.model.Content;
   10. import com.amazonaws.services.simpleemail.model.Destination;
   11. import com.amazonaws.services.simpleemail.model.Message;
   12. import com.amazonaws.services.simpleemail.model.SendEmailRequest; 
   13. 
   14. public class AmazonSESSample {
   15. 
   16.   // Replace sender@example.com with your "From" address.
   17.   // This address must be verified with Amazon SES.
   18.   static final String FROM = "sender@example.com";
   19. 
   20.   // Replace recipient@example.com with a "To" address. If your account
   21.   // is still in the sandbox, this address must be verified.
   22.   static final String TO = "recipient@example.com";
   23. 
   24.   // The configuration set to use for this email. If you do not want to use a
   25.   // configuration set, comment the following variable and the 
   26.   // .withConfigurationSetName(CONFIGSET); argument below.
   27.   static final String CONFIGSET = "ConfigSet";
   28. 
   29.   // The subject line for the email.
   30.   static final String SUBJECT = "Amazon SES test (適用於 Java 的 AWS SDK)";
   31.   
   32.   // The HTML body for the email.
   33.   static final String HTMLBODY = "<h1>Amazon SES test (適用於 Java 的 AWS SDK)</h1>"
   34.       + "<p>This email was sent with <a href='https://aws.amazon.com/ses/'>"
   35.       + "Amazon SES</a> using the <a href='https://aws.amazon.com/sdk-for-java/'>" 
   36.       + "AWS SDK for Java</a>";
   37. 
   38.   // The email body for recipients with non-HTML email clients.
   39.   static final String TEXTBODY = "This email was sent through Amazon SES "
   40.       + "using the 適用於 Java 的 AWS SDK.";
   41. 
   42.   public static void main(String[] args) throws IOException {
   43. 
   44.     try {
   45.       AmazonSimpleEmailService client = 
   46.           AmazonSimpleEmailServiceClientBuilder.standard()
   47.           // Replace US_WEST_2 with the AWS Region you're using for
   48.           // Amazon SES.
   49.             .withRegion(Regions.US_WEST_2).build();
   50.       SendEmailRequest request = new SendEmailRequest()
   51.           .withDestination(
   52.               new Destination().withToAddresses(TO))
   53.           .withMessage(new Message()
   54.               .withBody(new Body()
   55.                   .withHtml(new Content()
   56.                       .withCharset("UTF-8").withData(HTMLBODY))
   57.                   .withText(new Content()
   58.                       .withCharset("UTF-8").withData(TEXTBODY)))
   59.               .withSubject(new Content()
   60.                   .withCharset("UTF-8").withData(SUBJECT)))
   61.           .withSource(FROM)
   62.           // Comment or remove the next line if you are not using a
   63.           // configuration set
   64.           .withConfigurationSetName(CONFIGSET);
   65.       client.sendEmail(request);
   66.       System.out.println("Email sent!");
   67.     } catch (Exception ex) {
   68.       System.out.println("The email was not sent. Error message: " 
   69.           + ex.getMessage());
   70.     }
   71.   }
   72. }
   ```

1. 在 `AmazonSESSample.java` 中，以自訂值取代下列項目：
**重要**  
電子郵件地址會區分大小寫。請確認此地址與您已完成驗證的地址完全相同。
   + `SENDER@EXAMPLE.COM` - 以您的「寄件者」電子郵件地址取代。執行此程式前，須先驗證此地址。如需詳細資訊，請參閱 [在 Amazon SES 中驗證身分](verify-addresses-and-domains.md)。
   + `RECIPIENT@EXAMPLE.COM` - 以您的「收件人」電子郵件地址取代。如果您的帳戶仍在沙盒中，您必須在使用前先驗證這個地址。如需詳細資訊，請參閱「[請求生產存取權 （移出 Amazon SES 沙盒）](request-production-access.md)」。
   + **(選用)`us-west-2`** - 若您想要在美國西部 (奧勒岡) 以外的區域中使用 Amazon SES，請在您想要使用的區域中以此區域取代。如需可使用 Amazon SES 的區域清單，請參閱 *AWS 一般參考* 中的 [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)。

1. 儲存 `AmazonSESSample.java`。

1. 若要建置專案，請選擇 **Project (專案)**，然後選擇 **Build Project (建置專案)**。
**注意**  
如果此選項為停用，自動建立可能已啟用；若有此情況則可略過這個步驟。

1. 若要啟動程式並傳送電子郵件，請選擇 **Run (執行)**，然後再次選擇 **Run (執行)**。

1. 檢閱 Eclipse 中的主控台窗格輸出。若電子郵件成功傳送，主控台會顯示 "`Email sent!`" 否則，它會顯示錯誤訊息。

1. 如果電子郵件已成功傳送，請登入收件人地址的電子郵件用戶端。可以看到您已傳送的訊息。

------
#### [ PHP ]

此主題示範如何使用 [適用於 PHP 的 AWS SDK](https://aws.amazon.com/sdk-for-php/) 來透過 Amazon SES 傳送電子郵件。

**開始之前，請執行以下任務：**
+ **安裝 PHP** - PHP 可在 [http://php.net/downloads.php](http://php.net/downloads.php) 取得。此教學需要 PHP 版本 5.5 或更新版本。安裝 PHP 後，在環境變數中將路徑新增至 PHP，即可透過任何命令提示來執行 PHP。本教學中使用的程式碼使用 PHP 7.2.7 測試。
+ **安裝第 3 適用於 PHP 的 AWS SDK 版** - 如需下載和安裝說明，請參閱 [適用於 PHP 的 AWS SDK 文件](https://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html)。本教學中的程式碼使用版本 3.64.13 的軟體開發套件完成測試。

**使用 透過 Amazon SES 傳送電子郵件 適用於 PHP 的 AWS SDK**

1. 在文字編輯器中，建立名為 `amazon-ses-sample.php` 的檔案。貼上以下程式碼：

   ```
    1. <?php
    2. 
    3. // If necessary, modify the path in the require statement below to refer to the 
    4. // location of your Composer autoload.php file.
    5. require 'vendor/autoload.php';
    6. 
    7. use Aws\Ses\SesClient;
    8. use Aws\Exception\AwsException;
    9. 
   10. // Create an SesClient. Change the value of the region parameter if you're 
   11. // using an AWS Region other than US West (Oregon). Change the value of the
   12. // profile parameter if you want to use a profile in your credentials file
   13. // other than the default.
   14. $SesClient = new SesClient([
   15.     'profile' => 'default',
   16.     'version' => '2010-12-01',
   17.     'region'  => 'us-west-2'
   18. ]);
   19. 
   20. // Replace sender@example.com with your "From" address.
   21. // This address must be verified with Amazon SES.
   22. $sender_email = 'sender@example.com';
   23. 
   24. // Replace these sample addresses with the addresses of your recipients. If
   25. // your account is still in the sandbox, these addresses must be verified.
   26. $recipient_emails = ['recipient1@example.com','recipient2@example.com'];
   27. 
   28. // Specify a configuration set. If you do not want to use a configuration
   29. // set, comment the following variable, and the
   30. // 'ConfigurationSetName' => $configuration_set argument below.
   31. $configuration_set = 'ConfigSet';
   32. 
   33. $subject = 'Amazon SES test (適用於 PHP 的 AWS SDK)';
   34. $plaintext_body = 'This email was sent with Amazon SES using the AWS SDK for PHP.' ;
   35. $html_body =  '<h1>AWS Amazon Simple Email Service Test Email</h1>'.
   36.               '<p>This email was sent with <a href="https://aws.amazon.com/ses/">'.
   37.               'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-php/">'.
   38.               '適用於 PHP 的 AWS SDK</a>.</p>';
   39. $char_set = 'UTF-8';
   40. 
   41. try {
   42.     $result = $SesClient->sendEmail([
   43.         'Destination' => [
   44.             'ToAddresses' => $recipient_emails,
   45.         ],
   46.         'ReplyToAddresses' => [$sender_email],
   47.         'Source' => $sender_email,
   48.         'Message' => [
   49.           'Body' => [
   50.               'Html' => [
   51.                   'Charset' => $char_set,
   52.                   'Data' => $html_body,
   53.               ],
   54.               'Text' => [
   55.                   'Charset' => $char_set,
   56.                   'Data' => $plaintext_body,
   57.               ],
   58.           ],
   59.           'Subject' => [
   60.               'Charset' => $char_set,
   61.               'Data' => $subject,
   62.           ],
   63.         ],
   64.         // If you aren't using a configuration set, comment or delete the
   65.         // following line
   66.         'ConfigurationSetName' => $configuration_set,
   67.     ]);
   68.     $messageId = $result['MessageId'];
   69.     echo("Email sent! Message ID: $messageId"."\n");
   70. } catch (AwsException $e) {
   71.     // output error message if fails
   72.     echo $e->getMessage();
   73.     echo("The email was not sent. Error message: ".$e->getAwsErrorMessage()."\n");
   74.     echo "\n";
   75. }
   ```

1. 在 `amazon-ses-sample.php` 中，以自訂值取代下列項目：
   + **`path_to_sdk_inclusion`**- 取代為在程式 適用於 PHP 的 AWS SDK 中包含 所需的路徑。如需詳細資訊，請參閱 [適用於 PHP 的 AWS SDK 文件](https://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/basic-usage.html)。
   + **`sender@example.com`** - 以您已透過 Amazon SES 驗證的電子郵件地址來取代。如需詳細資訊，請參閱 [驗證身分](verify-addresses-and-domains.md)。Amazon SES 中的電子郵件地址會區分大小寫。請確認您輸入的地址與您已完成驗證的地址完全相同。
   + **`recipient1@example.com`、`recipient2@example.com`**—以收件人的地址取代。若您的帳戶仍在沙盒中，您也必須驗證您收件人的地址。如需詳細資訊，請參閱「[請求生產存取權 （移出 Amazon SES 沙盒）](request-production-access.md)」。請確認您輸入的地址與您已完成驗證的地址完全相同。
   + **(選用)`ConfigSet`** - 若您希望在傳送此電子郵件時使用組態集，請用組態集的名稱取代此值。如需組態集的詳細資訊，請參閱 [使用 Amazon SES 中的組態集](using-configuration-sets.md)。
   + **(選用)`us-west-2`** - 若您想要在美國西部 (奧勒岡) 以外的區域中使用 Amazon SES，請在您想要使用的區域中以此區域取代。如需可使用 Amazon SES 的區域清單，請參閱 *AWS 一般參考* 中的 [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)。

1. 儲存 `amazon-ses-sample.php`。

1. 若要執行程式，請在與 `amazon-ses-sample.php` 相同的目錄中開啟命令提示，然後輸入以下命令：

   ```
   $ php amazon-ses-sample.php
   ```

1. 檢閱輸出。若電子郵件成功傳送，主控台會顯示 "`Email sent!`" 否則，它會顯示錯誤訊息。
**注意**  
若在執行程式時發生 "cURL error 60: SSL certificate problem" (cURL 錯誤 60：SSL 憑證問題) 錯誤，請下載最新的 CA bundle，如 [適用於 PHP 的 AWS SDK 文件](https://docs.aws.amazon.com/aws-sdk-php/v3/guide/faq.html#what-do-i-do-about-a-curl-ssl-certificate-error)中所述。然後，在 `amazon-ses-sample.php` 中，新增下列幾行到 `SesClient::factory` 陣列，以前往 CA bundle 的下載路徑取代 `path_of_certs`，然後重新執行程式。  

   ```
   1. 'http' => [
   2.    'verify' => 'path_of_certs\ca-bundle.crt'
   3. ]
   ```

1. 登入收件人地址的電子郵件用戶端。可以看到您已傳送的訊息。

------
#### [ Ruby ]

此主題示範如何使用 [適用於 Ruby 的 AWS SDK](https://aws.amazon.com/sdk-for-ruby/) 來透過 Amazon SES 傳送電子郵件。

**開始之前，請執行以下任務：**
+ **安裝 Ruby** - Ruby 可在 [https://www.ruby-lang.org/en/downloads/](https://www.ruby-lang.org/en/downloads/) 取得。本教學中使用的程式碼已使用 Ruby 1.9.3 測試。在您安裝 Ruby 後，請在環境變數中新增指向 Ruby 的路徑，讓您可以從任何命令提示執行 Ruby。
+ **安裝 適用於 Ruby 的 AWS SDK**- 如需下載和安裝說明，請參閱[《 開發人員指南》中的安裝 適用於 Ruby 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-ruby/latest/developer-guide/setup-install.html) 。 *適用於 Ruby 的 AWS SDK *此教學中的範本程式碼使用 適用於 Ruby 的 AWS SDK版本 2.9.36 測試。
+ **建立共用憑證檔案** - 為讓本節中的範本程式碼正常運作，須建立共用憑證檔案。如需詳細資訊，請參閱[建立共用登入資料檔案，以便在使用 AWS SDK 透過 Amazon SES 傳送電子郵件時使用](create-shared-credentials-file.md)。

**使用 透過 Amazon SES 傳送電子郵件 適用於 Ruby 的 AWS SDK**

1. 在文字編輯器中，建立名為 `amazon-ses-sample.rb` 的檔案。將以下程式碼貼到檔案：

   ```
    1. require 'aws-sdk'
    2. 
    3. # Replace sender@example.com with your "From" address.
    4. # This address must be verified with Amazon SES.
    5. sender = "sender@example.com"
    6. 
    7. # Replace recipient@example.com with a "To" address. If your account 
    8. # is still in the sandbox, this address must be verified.
    9. recipient = "recipient@example.com"
   10. 
   11. # Specify a configuration set. If you do not want to use a configuration
   12. # set, comment the following variable and the 
   13. # configuration_set_name: configsetname argument below. 
   14. configsetname = "ConfigSet"
   15.   
   16. # Replace us-west-2 with the AWS Region you're using for Amazon SES.
   17. awsregion = "us-west-2"
   18. 
   19. # The subject line for the email.
   20. subject = "Amazon SES test (適用於 Ruby 的 AWS SDK)"
   21. 
   22. # The HTML body of the email.
   23. htmlbody =
   24.   '<h1>Amazon SES test (適用於 Ruby 的 AWS SDK)</h1>'\
   25.   '<p>This email was sent with <a href="https://aws.amazon.com/ses/">'\
   26.   'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-ruby/">'\
   27.   '適用於 Ruby 的 AWS SDK</a>.'
   28. 
   29. # The email body for recipients with non-HTML email clients.  
   30. textbody = "This email was sent with Amazon SES using the 適用於 Ruby 的 AWS SDK."
   31. 
   32. # Specify the text encoding scheme.
   33. encoding = "UTF-8"
   34. 
   35. # Create a new SES resource and specify a region
   36. ses = Aws::SES::Client.new(region: awsregion)
   37. 
   38. # Try to send the email.
   39. begin
   40. 
   41.   # Provide the contents of the email.
   42.   resp = ses.send_email({
   43.     destination: {
   44.       to_addresses: [
   45.         recipient,
   46.       ],
   47.     },
   48.     message: {
   49.       body: {
   50.         html: {
   51.           charset: encoding,
   52.           data: htmlbody,
   53.         },
   54.         text: {
   55.           charset: encoding,
   56.           data: textbody,
   57.         },
   58.       },
   59.       subject: {
   60.         charset: encoding,
   61.         data: subject,
   62.       },
   63.     },
   64.   source: sender,
   65.   # Comment or remove the following line if you are not using 
   66.   # a configuration set
   67.   configuration_set_name: configsetname,
   68.   })
   69.   puts "Email sent!"
   70. 
   71. # If something goes wrong, display an error message.
   72. rescue Aws::SES::Errors::ServiceError => error
   73.   puts "Email not sent. Error message: #{error}"
   74. 
   75. end
   ```

1. 在 `amazon-ses-sample.rb` 中，以自訂值取代下列項目：
   + **`sender@example.com`** - 以您已透過 Amazon SES 驗證的電子郵件地址來取代。如需詳細資訊，請參閱 [驗證身分](verify-addresses-and-domains.md)。Amazon SES 中的電子郵件地址會區分大小寫。請確認您輸入的地址與您已完成驗證的地址完全相同。
   + **`recipient@example.com`** - 以收件人的地址取代。如果您的帳戶仍在沙盒中，您必須在使用前先驗證這個地址。如需詳細資訊，請參閱 [請求生產存取權 （移出 Amazon SES 沙盒）](request-production-access.md)。請確認您輸入的地址與您已完成驗證的地址完全相同。
   + **(選用)`us-west-2`** - 若您想要在美國西部 (奧勒岡) 以外的區域中使用 Amazon SES，請在您想要使用的區域中以此區域取代。如需可使用 Amazon SES 的區域清單，請參閱 *AWS 一般參考* 中的 [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)。

1. 儲存 `amazon-ses-sample.rb`。

1. 若要執行程式，請在與 `amazon-ses-sample.rb` 相同的目錄中開啟命令提示，然後輸入 **ruby amazon-ses-sample.rb**

1. 檢閱輸出。若電子郵件成功傳送，主控台會顯示 "`Email sent!`" 否則，它會顯示錯誤訊息。

1. 登入收件人地址的電子郵件用戶端。可以找到您已傳送的訊息。

------
#### [ Python ]

此主題示範如何使用 [適用於 Python (Boto) 的 AWS SDK](https://aws.amazon.com/sdk-for-python/) 來透過 Amazon SES 傳送電子郵件。

**開始之前，請執行以下任務：**
+ **以 Amazon SES 驗證您的電子郵件地址** - 您必須先驗證您為寄件者電子郵件地址的擁有者，才可以使用 Amazon SES 傳送電子郵件。如果您的帳戶仍在 Amazon SES 沙盒中，您必須同時驗證收件人地址。建議您使用 Amazon SES 主控台來驗證電子郵件地址。如需詳細資訊，請參閱[建立電子郵件地址身分](creating-identities.md#verify-email-addresses-procedure)。
+ **取得您的 AWS 登入**資料 - 您需要 AWS 存取金鑰 ID 和 AWS 私密存取金鑰，才能使用 SDK 存取 Amazon SES。您可以使用 AWS 管理主控台的[安全憑證](https://console.aws.amazon.com/iam/home?#security_credential)頁面找到您的憑證。如需憑證的詳細資訊，請參閱 [Amazon SES 憑證的類型](send-email-concepts-credentials.md)。
+ **安裝 Python** - Python 可在 [https://www.python.org/downloads/](https://www.python.org/downloads/) 下載。本教學中的程式碼已使用 Python 2.7.6 版及 Python 3.6.1 版測試。在您安裝 Python 後，請在環境變數中新增指向 Python 的路徑，讓您可以從任何命令提示執行 Python。
+ **安裝 適用於 Python (Boto) 的 AWS SDK**- 如需下載和安裝說明，請參閱 [適用於 Python (Boto) 的 AWS SDK 文件](https://boto3.readthedocs.io/en/latest/guide/quickstart.html#installation)。此教學中的範本程式碼使用適用於 Python 的軟體開發套件 1.4.4 版進行測試。

**使用適用於 Python 的軟體開發套件透過 Amazon SES 傳送電子郵件**

1. 在文字編輯器中，建立名為 `amazon-ses-sample.py` 的檔案。將以下程式碼貼到檔案：

   ```
    1. import boto3
    2. from botocore.exceptions import ClientError
    3. 
    4. # Replace sender@example.com with your "From" address.
    5. # This address must be verified with Amazon SES.
    6. SENDER = "Sender Name <sender@example.com>"
    7. 
    8. # Replace recipient@example.com with a "To" address. If your account 
    9. # is still in the sandbox, this address must be verified.
   10. RECIPIENT = "recipient@example.com"
   11. 
   12. # Specify a configuration set. If you do not want to use a configuration
   13. # set, comment the following variable, and the 
   14. # ConfigurationSetName=CONFIGURATION_SET argument below.
   15. CONFIGURATION_SET = "ConfigSet"
   16. 
   17. # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
   18. AWS_REGION = "us-west-2"
   19. 
   20. # The subject line for the email.
   21. SUBJECT = "Amazon SES Test (SDK for Python)"
   22. 
   23. # The email body for recipients with non-HTML email clients.
   24. BODY_TEXT = ("Amazon SES Test (Python)\r\n"
   25.              "This email was sent with Amazon SES using the "
   26.              "適用於 Python (Boto) 的 AWS SDK."
   27.             )
   28.             
   29. # The HTML body of the email.
   30. BODY_HTML = """<html>
   31. <head></head>
   32. <body>
   33.   <h1>Amazon SES Test (SDK for Python)</h1>
   34.   <p>This email was sent with
   35.     <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the
   36.     <a href='https://aws.amazon.com/sdk-for-python/'> 適用於 Python (Boto) 的 AWS SDK</a>.</p>
   37. </body>
   38. </html>
   39.             """            
   40. 
   41. # The character encoding for the email.
   42. CHARSET = "UTF-8"
   43. 
   44. # Create a new SES resource and specify a region.
   45. client = boto3.client('ses',region_name=AWS_REGION)
   46. 
   47. # Try to send the email.
   48. try:
   49.     #Provide the contents of the email.
   50.     response = client.send_email(
   51.         Destination={
   52.             'ToAddresses': [
   53.                 RECIPIENT,
   54.             ],
   55.         },
   56.         Message={
   57.             'Body': {
   58.                 'Html': {
   59.                     'Charset': CHARSET,
   60.                     'Data': BODY_HTML,
   61.                 },
   62.                 'Text': {
   63.                     'Charset': CHARSET,
   64.                     'Data': BODY_TEXT,
   65.                 },
   66.             },
   67.             'Subject': {
   68.                 'Charset': CHARSET,
   69.                 'Data': SUBJECT,
   70.             },
   71.         },
   72.         Source=SENDER,
   73.         # If you are not using a configuration set, comment or delete the
   74.         # following line
   75.         ConfigurationSetName=CONFIGURATION_SET,
   76.     )
   77. # Display an error if something goes wrong.	
   78. except ClientError as e:
   79.     print(e.response['Error']['Message'])
   80. else:
   81.     print("Email sent! Message ID:"),
   82.     print(response['MessageId'])
   ```

1. 在 `amazon-ses-sample.py` 中，以自訂值取代下列項目：
   + **`sender@example.com`** - 以您已透過 Amazon SES 驗證的電子郵件地址來取代。如需詳細資訊，請參閱[驗證身分](verify-addresses-and-domains.md)。Amazon SES 中的電子郵件地址會區分大小寫。請確認您輸入的地址與您已完成驗證的地址完全相同。
   + **`recipient@example.com`** - 以收件人的地址取代。如果您的帳戶仍在沙盒中，您必須在使用前先驗證這個地址。如需詳細資訊，請參閱 [請求生產存取權 （移出 Amazon SES 沙盒）](request-production-access.md)。請確認您輸入的地址與您已完成驗證的地址完全相同。
   + **(選用)`us-west-2`** - 若您想要在美國西部 (奧勒岡) 以外的區域中使用 Amazon SES，請在您想要使用的區域中以此區域取代。如需可使用 Amazon SES 的區域清單，請參閱 *AWS 一般參考* 中的 [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)。

1. 儲存 `amazon-ses-sample.py`。

1. 若要執行程式，請在與 `amazon-ses-sample.py` 相同的目錄中開啟命令提示，然後輸入 **python amazon-ses-sample.py**。

1. 檢閱輸出。若電子郵件成功傳送，主控台會顯示 "`Email sent!`" 否則，它會顯示錯誤訊息。

1. 登入收件人地址的電子郵件用戶端。可以看到您已傳送的訊息。

------

# 建立共用登入資料檔案，以便在使用 AWS SDK 透過 Amazon SES 傳送電子郵件時使用
<a name="create-shared-credentials-file"></a>

下列程序說明如何在目錄中建立共用的憑證檔案。為讓開發套件範本程式碼正常運作，您必須建立此檔案。

1. 在文字編輯器中，建立新檔案。在檔案中貼上下方程式碼：

   ```
   1. [default]
   2. aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
   3. aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY
   ```

1. 在您剛建立的文字檔案中，將 取代`YOUR_AWS_ACCESS_KEY`為您唯一的 AWS 存取金鑰 ID，並將 取代`YOUR_AWS_SECRET_ACCESS_KEY`為您唯一的 AWS 私密存取金鑰。

1. 儲存檔案。下表顯示作業系統的正確位置和檔案名稱。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/ses/latest/dg/create-shared-credentials-file.html)
**重要**  
儲存憑證檔案時請勿包含副檔名。

# Amazon SES 支援的內容編碼
<a name="content-encodings"></a>

以下內容供參考。

Amazon SES 支援下列內容編碼：
+ `deflate`
+ `gzip`
+ `identity`

根據 [RFC 7231 規格](https://tools.ietf.org/html/rfc7231#section-5.3.4)，Amazon SES 也支援下列 Accept-Encoding 標頭格式：
+ `Accept-Encoding:deflate,gzip`
+ `Accept-Encoding:`
+ `Accept-Encoding:*`
+ `Accept-Encoding:deflate;q=0.5,gzip;q=1.0`
+ `Accept-Encoding:gzip;q=1.0,identity;q=0.5,*;q=0`

# Amazon SES 和安全通訊協定
<a name="security-protocols"></a>

本主題說明在連線至 Amazon SES 以及 Amazon SES 遞送郵件給接收者時，可使用的安全通訊協定。

## 電子郵件寄件者對 Amazon SES
<a name="security-client-to-ses"></a>

您連線至 Amazon SES 所使用的安全通訊協定，取決於您使用的是 Amazon SES API 還是 Amazon SES SMTP 界面，詳情如下。

### HTTPS
<a name="security-client-to-ses-api"></a>

如果您使用 Amazon SES API （直接或透過 AWS SDK)，則所有通訊都會透過 Amazon SES HTTPS 端點由 TLS 加密。Amazon SES HTTPS 端點支援 TLS 1.2 和 TLS 1.3。

### SMTP 界面
<a name="security-client-to-ses-smtp"></a>

如果您透過 SMTP 界面存取 Amazon SES，則需使用 Transport Layer Security (TLS) 加密連線。請注意，TLS 通常是指前置工作通訊協定的名稱，Secure Sockets Layer (SSL)。

Amazon SES 支援透過兩種機制來建立 TLS 加密連線：STARTTLS 和 TLS Wrapper。
+ **STARTTLS** - STARTTLS 是一種將未加密連線升級為加密連線的方法。各種通訊協定適用的 STARTTLS 版本各不相同，[RFC 3207](https://www.ietf.org/rfc/rfc3207.txt) 定有 SMTP 版本的規範。對於 STARTTLS 連線，Amazon SES 支援 TLS 1.2 和 TLS 1.3。
+ **TLS Wrapper** - TLS Wrapper (也稱為 SMTPS 或 Handshake 通訊協定) 是一種無需先建立未加密連線來啟動加密連線的方法。使用 TLS Wrapper 時，Amazon SES SMTP 端點不會執行 TLS 交涉：使用 TLS 連接端點、在整個對話過程中使用 TLS 來繼續等工作都是用戶端的責任。TLS Wrapper 是較舊的通訊協定，但是仍受許多用戶端支援。針對 TLS Wrapper 連線，Amazon SES 支援 TLS 1.2 和 TLS 1.3。

如需使用這些方法連線至 Amazon SES SMTP 界面的資訊，請參閱「[連線到 Amazon SES SMTP 端點](smtp-connect.md)」。

## Amazon SES 對接收者
<a name="security-ses-to-receiver"></a>

 雖然 TLS 1.3 是我們的預設交付方法，但 SES 可以使用舊版 TLS 將電子郵件交付至郵件伺服器。

預設情況下，Amazon SES 使用*隨機 TLS*。SES 中的機會式 TLS 一律使用 STARTTLS，且不包含 TLS 包裝函式。如果用戶端和伺服器都支援 STARTTLS，流程會涉及建立初始純文字連線，然後升級至 TLS 加密工作階段。如果 SES 無法建立安全連線，它會傳送未加密的訊息。

您可以透過使用組態集來變更這種行為。使用 [PutConfigurationSetDeliveryOptions](https://docs.aws.amazon.com/ses/latest/APIReference/API_PutConfigurationSetDeliveryOptions.html) API 操作來將組態集的 `TlsPolicy` 屬性設為 `Require`。您可以使用 [AWS CLI](https://aws.amazon.com/cli) 來進行此變更。

**將 Amazon SES 設定為需要組態集的 TLS 連線**
+ 在命令列中輸入以下命令：

  ```
  aws sesv2 put-configuration-set-delivery-options --configuration-set-name MyConfigurationSet --tls-policy REQUIRE
  ```

  在上述範例中，使用您組態集的名稱來取代 *MyConfigurationSet*。

  如果 Amazon SES 能建立安全連線，當您傳送使用此組態集的電子郵件時，就只會將此訊息傳送至接收電子郵件伺服器。如果 Amazon SES 無法與接收電子郵件伺服器建立安全連線，則會捨棄此訊息。

## 端對端加密
<a name="security-end-to-end"></a>

您可以使用 Amazon SES 傳送以 S/MIME 或 PGP 加密的訊息。使用這些通訊協定的訊息會由寄件者加密。其內容只能由擁有解密訊息所需之私有金鑰的收件人檢視。

Amazon SES 支援以下 MIME 類型，您可以用來傳送 S/MIME 加密的電子郵件：
+ `application/pkcs7-mime`
+ `application/pkcs7-signature`
+ `application/x-pkcs7-mime`
+ `application/x-pkcs7-signature`

Amazon SES 也支援以下 MIME 類型，您可以用來傳送 PGP 加密的電子郵件：
+ `application/pgp-encrypted`
+ `application/pgp-keys`
+ `application/pgp-signature`

# Amazon SES 標頭欄位
<a name="header-fields"></a>

Amazon SES 可接受所有遵循 [RFC 822](https://www.rfc-editor.org/rfc/rfc822.html) 所述格式的電子郵件標頭。

下列欄位無法在訊息的標頭區段中顯示超過一次：
+ `Accept-Language`
+ `acceptLanguage`
+ `Archived-At`
+ `Auto-Submitted`
+ `Bounces-to`
+ `Comments`
+ `Content-Alternative`
+ `Content-Base`
+ `Content-Class`
+ `Content-Description`
+ `Content-Disposition`
+ `Content-Duration`
+ `Content-ID`
+ `Content-Language`
+ `Content-Length`
+ `Content-Location`
+ `Content-MD5`
+ `Content-Transfer-Encoding`
+ `Content-Type`
+ `Date`
+ `Delivered-To `
+ `Disposition-Notification-Options`
+ `Disposition-Notification-To`
+ `DKIM-Signature`
+ `DomainKey-Signature`
+ `Errors-To`
+ `From`
+ `Importance`
+ `In-Reply-To`
+ `Keywords`
+ `List-Archive`
+ `List-Help`
+ `List-Id`
+ `List-Owner`
+ `List-Post`
+ `List-Subscribe`
+ `List-Unsubscribe`
+ `List-Unsubscribe-Post`
+ `Message-Context`
+ `Message-ID`
+ `MIME-Version`
+ `Organization`
+ `Original-From`
+ `Original-Message-ID`
+ `Original-Recipient`
+ `Original-Subject`
+ `Precedence`
+ `Priority`
+ `References`
+ `Reply-To`
+ `Return-Path`
+ `Return-Receipt-To`
+ `Sender`
+ `Solicitation`
+ `Sensitivity`
+ `Subject`
+ `Thread-Index`
+ `Thread-Topic`
+ `User-Agent`
+ `VBR-Info`

**考量事項**
+ 此 `acceptLanguage` 欄位為非標準欄位。如果可能，您應該改為使用 `Accept-Language` 標頭。
+ 如果您指定 `Date` 標頭，當 Amazon SES 接受訊息時，會以對應至 UTC 時區之日期和時間的時間戳記來覆寫標頭。
+ 如果您提供 `Message-ID` 標頭，Amazon SES 會以自己的值覆寫標頭。
+ 如果您指定 `Return-Path` 標頭，Amazon SES 會傳送退信和投訴通知到您指定的地址。不過，收件人收到的訊息包含不同的 `Return-Path` 標頭值。
+ 如果您使用 Amazon SES API v2 `SendEmail`操作搭配*簡易*或*範本*內容，或使用 `SendBulkEmail`操作，則無法為 SES 設定的標頭設定自訂標頭內容；因此，不允許以下標頭做為自訂標頭：
  + `BCC`, `CC`, `Content-Disposition`, `Content-Type`, `Date`, `From`, `Message-ID`, `MIME-Version`, `Reply-To`, `Return-Path`, `Subject`, `To`

# 在 SES 中使用電子郵件附件
<a name="attachments"></a>

SES 中的電子郵件附件是您可以在使用 SES API v2 `SendEmail`和 `SendBulkEmail`操作時包含在電子郵件訊息中的檔案。此功能可讓您透過包含 PDFs、Word 檔案、映像或其他符合 SES 支援 MIME 類型的檔案類型，來豐富您的電子郵件內容。您也可以包含直接在電子郵件內容中轉譯的內嵌影像，而不需要收件人單獨下載。每封電子郵件可以包含多個附件，總訊息大小上限為 40MB。

**注意**  
[https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html) 具有`Raw`內容類型、SMTP 界面和 SES API v1 的 SES API v2 會透過[原始電子郵件 MIME 訊息建構](send-email-raw.md#send-email-raw-mime)繼續處理附件。

## 附件在 SES 中的運作方式
<a name="how-attachments-work"></a>

使用附件傳送電子郵件時，在不同的階段會發生兩種不同類型的編碼：

階段 1 – 將資料傳送至 SES：
+ 當您想要將附件傳送至 SES 時，二進位資料 （例如 PDF 或影像） 需要轉換為可安全傳輸的格式。
+ 這是 base64 編碼傳入的位置，這是必要的，因為您無法在 JSON 請求中傳送原始二進位資料。
+ 如果您使用 AWS SDK，則會自動處理此編碼。
+ 如果您使用的是 AWS CLI，則需要先自行對附件進行 base64 編碼，再傳送附件。

階段 2 – 建立電子郵件的 SES：
+ 一旦 SES 收到您的資料，它需要建立附有附件的實際電子郵件。
+ 這是 [ContentTransferEncoding](#attachment-structure) 設定發揮作用的位置。
+ SES 將使用您在 ContentTransferEncoding 中指定的任何編碼方法，自動格式化最終電子郵件中的附件。

想像一下，它類似於透過郵件傳送套件。首先，您需要將套件取得至郵局 （需要階段 1 - Base64-encoding)，然後郵局會妥善封裝以進行最終交付 （階段 2 - ContentTransferEncoding)。

## 附件物件結構
<a name="attachment-structure"></a>

當您透過 SES 傳送含有附件的電子郵件時，服務會自動處理複雜的 MIME 訊息建構。您只需要透過下列 SES API v2 [https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Attachment.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Attachment.html) 物件結構提供附件內容和中繼資料：
+ `FileName` （必要） – 向收件人顯示的檔案名稱 （必須包含副檔名）。如果未提供，SES 將從 `ContentType` 的延伸衍生 `FileName`。
+ `ContentType` （選用） – [IANA 相容媒體類型識別符](https://www.iana.org/assignments/media-types/media-types.xhtml)。
+ `ContentDisposition` （選用） – 指定應如何轉譯附件： `ATTACHMENT` *（預設）* 或 `INLINE`。
+ `ContentDescription` （選用） – 內容的簡短描述。
+ `RawContent` （必要） – 附件的實際內容。
+ `ContentTransferEncoding` （選用） – 指定附件承載在組合成電子郵件的 mime 訊息時如何編碼： `SEVEN_BIT`*（預設）* `BASE64`或 `QUOTED_PRINTABLE`。

所有連接的內容都必須編碼為 base64，才能轉移到 SES 端點進行傳送。如果您使用 AWS SDK 用戶端進行 API 呼叫，系統會自動為您處理。如果您使用的是 AWS CLI，或已實作自己的用戶端，則必須自行執行編碼，例如：
+ 純文字內容： `Text attachment sample content.`
+ Base64 編碼： `VGV4dCBhdHRhY2htZW50IHNhbXBsZSBjb250ZW50Lg==`

下列範例示範如何在使用 AWS CLI 參考包含附件物件元素的 JSON 檔案，透過 SES API v2 [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_SendBulkEmail.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendBulkEmail.html)操作指定附件時，使用附件物件結構。

**Example – 包含簡單內容的 SendEmail**  

```
aws sesv2 send-email --cli-input-json file://request-send-email-simple.json
```
**request-send-email-simple.json**  

```
{
    "FromEmailAddress": "sender@example.com",
    "Destination": {
        "ToAddresses": [
            "recipient@example.com"
        ]
    },
    "Content": {
        "Simple": {
            "Subject": {
                "Data": "Email with attachment"
            },
            "Body": {
                "Text": {
                    "Data": "Please see attached document."
                },
                "Html": {
                    "Data": "Please see attached <b>document</b>."
                }
            },
            "Attachments": [
                {
                    "RawContent": "<base64-encoded-content>",
                    "ContentDisposition": "ATTACHMENT",
                    "FileName": "document.pdf",
                    "ContentDescription": "PDF Document Attachment",
                    "ContentTransferEncoding": "BASE64"
                }
            ]
        }
    }
}
```

**Example – 包含簡單內容和內嵌附件的 SendEmail**  

```
aws sesv2 send-email --cli-input-json file://request-send-email-simple-inline-attachment.json
```
**request-send-email-simple-inline-attachment.json**  

```
{
    "FromEmailAddress": "sender@example.com",
    "Destination": {
        "ToAddresses": [
            "recipient@example.com"
        ]
    },
    "Content": {
        "Simple": {
            "Subject": {
                "Data": "Email with attachment"
            },
            "Body": {
                "Html": {
                    "Data": "<html><body>Our logo:<br><img src=\"cid:logo123\" alt=\"Company Logo\"></body></html>"
                }
            },
            "Attachments": [
                {
                    "RawContent": "<base64-encoded-content>",
                    "ContentDisposition": "INLINE",
                    "FileName": "logo.png",
                    "ContentId": "logo123",
                    "ContentTransferEncoding": "BASE64"
                }
            ]
        }
    }
}
```

**Example – SendEmail 與範本內容**  

```
aws sesv2 send-email --cli-input-json file://request-send-email-template.json
```
**request-send-email-template.json**  

```
{
    "FromEmailAddress": "sender@example.com",
    "Destination": {
        "ToAddresses": [
            "recipient@example.com"
        ]
    },
    "Content": {
        "Template": {
            "TemplateName": "MyTemplate",
            "TemplateData": "{\"name\":\"John\"}",
            "Attachments": [
                {
                    "RawContent": "<base64-encoded-content>",
                    "ContentDisposition": "ATTACHMENT",
                    "FileName": "document.pdf",
                    "ContentDescription": "PDF Document Attachment",
                    "ContentTransferEncoding": "BASE64"
                }
            ]
        }
    }
}
```

**Example – SendBulkEmail 含附件內容**  

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

```
{
    "FromEmailAddress": "sender@example.com",
    "DefaultContent": {
        "Template": {
            "TemplateName": "MyTemplate",
            "TemplateData": "{}",
            "Attachments": [
                {
                    "RawContent": "<base64-encoded-content>",
                    "ContentDisposition": "ATTACHMENT",
                    "FileName": "document.pdf",
                    "ContentDescription": "PDF Document Attachment",
                    "ContentTransferEncoding": "BASE64"
                }
            ]
        }
    },
    "BulkEmailEntries": [
        {
            "Destination": {
                "ToAddresses": [
                    "recipient@example.com"
                ]
            },
            "ReplacementEmailContent": {
                "ReplacementTemplate": {
                    "ReplacementTemplateData": "{\"name\":\"John\"}"
                }
            }
        }
    ]
}
```

## 最佳實務
<a name="attachments-best-practices"></a>
+ 將總訊息大小 （包括附件） 保持在 40MB 以下。
+ 讓 SES 盡可能根據副檔名自動偵測內容類型。
+ 只有當內容類型落在[常見 MIME 類型之外時，才明確指定內容類型](https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types/Common_types)。
+ 請考慮使用內嵌影像以獲得更好的電子郵件轉譯。
+ SES 支援各種 MIME 類型的附件，但 中列出的類型除外[不支援的附件類型](#mime-types)。

## SES 不支援的附件類型
<a name="mime-types"></a>

您可以使用多用途網際網路郵件延伸 (MIME) 標準，透過 Amazon SES 傳送含有附件的訊息。Amazon SES 接受所有檔案附件類型，含有列於下列清單中的副檔名之附件*除外*。


|  |  |  |  |  | 
| --- |--- |--- |--- |--- |
| .ade .adp .app .asp .bas .bat .cer .chm .cmd .com .cpl .crt .csh .der .exe .fxp .gadget .hlp  | .hta .inf .ins .isp .its .js .jse .ksh .lib .lnk .mad .maf .mag .mam .maq .mar .mas .mat  | .mau .mav .maw .mda .mdb .mde .mdt .mdw .mdz .msc .msh .msh1 .msh2 .mshxml .msh1xml .msh2xml .msi .msp  | .mst .ops .pcd .pif .plg .prf .prg .reg .scf .scr .sct .shb .shs .sys .ps1 .ps1xml .ps2 .ps2xml  | .psc1 .psc2 .tmp .url .vb .vbe .vbs .vps .vsmacros .vss .vst .vsw .vxd .ws .wsc .wsf .wsh .xnk  | 

部分 ISP 可能有其他限制 (例如關於封存的附件之限制)，因此我們建議在傳送生產電子郵件時先針對透過主要 ISP 執行的電子郵件傳送進行測試。