

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

# 使用 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. 登入收件人地址的電子郵件用戶端。可以看到您已傳送的訊息。

------