

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

# 使用软件开发工具包通过 Amazon AWS SES 发送电子邮件
<a name="send-an-email-using-sdk-programmatically"></a>

您可以使用 AWS 软件开发工具包通过 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 证书**-您需要访问密钥 ID 和 AWS 私有 AWS 访问密钥才能使用软件开发工具包访问 Amazon SES。您可以使用 [中的](https://console.aws.amazon.com/iam/home?#security_credential)安全凭证 AWS 管理控制台页面来查找您的凭证。有关凭证的更多信息，请参阅[Amazon SES 凭证的类型](send-email-concepts-credentials.md)。
+ **创建共享凭证文件** – 为了使此部分中的示例代码正常运行，您必须创建一个共享凭证文件。有关更多信息，请参阅 [创建共享凭证文件，以便在使用软件开发工具包通过 Amazon AWS 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。
+  AWSSDK.Core 软件包（版本 3.3.19），使用安装。 NuGet
+ 的 AWSSDK。 SimpleEmail 软件包（版本 3.3.6.1），使用安装。 NuGet

**在开始前，请执行以下任务：**
+ **安装 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. 对于**名称**，键入 **AmazonSESSample**，然后选择 **确定**。

1. 通过完成以下步骤，使用 NuGet 将 Amazon SES 软件包包含在您的解决方案中：

   1. 在 “**解决方案资源管理器**” 窗格中，右键单击您的项目，然后选择 “**管理 NuGet 包**”。

   1. 在 **NuGet：Amazon SESSample** 选项卡上，选择**浏览**。

   1. 在搜索框中，键入 **AWSSDK.SimpleEmail**。

   1. 选择**AWSSDK。 SimpleEmail**软件包，然后选择 “**安装**”。

   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)。
   + *recipient@example.com*替换为 “收件人：” 地址。如果您的账户仍处于沙盒中，则还必须验证此地址。
   + *ConfigSet*替换为发送此电子邮件时要使用的配置集的名称。
   + *USWest2*替换为您用于通过 Amazon SES 发送电子邮件的 AWS 区域 终端节点的名称。有关已推出 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、[AWS Toolkit for Eclipse](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)如何创建软件开发](http://www.eclipse.org/) AWS 工具包项目和修改 Java 代码以通过 Amazon SES 发送电子邮件。

**在开始前，请执行以下任务：**
+ **安装 Eclipse**：访问 [https://www.eclipse.org/downloads](https://www.eclipse.org/downloads) 可获得 Eclipse。本教程中的代码使用 Eclipse Neon.3（版本 4.6.3） 和 Java 运行时环境的 1.8 版本进行了测试。
+ **安装 AWS Toolkit for Eclipse** [—有关向 Eclipse 安装中 AWS Toolkit for Eclipse 添加的说明，请访问 /eclipse。https://aws.amazon.com](https://aws.amazon.com/eclipse)本教程中的代码已使用 2.3.1 版本的 AWS Toolkit for Eclipse进行了测试。

**要使用发送电子邮件 适用于 Java 的 AWS SDK**

1. 通过执行以下步骤在 Eclipse 中创建 AWS Java 项目：

   1. 启动 Eclipse。

   1. 在 **File** 菜单上，选择 **New**，然后选择 **Other**。在 **New** 窗口中，展开 **AWS** 文件夹，然后选择 **AWS Java Project**。

   1. 在 “**新建 AWS Java 项目**” 对话框中，执行以下操作：

      1. 对于 **Project name**，键入项目的名称。

      1. 在 “**适用于 Java 的 AWS SDK 示例**” 下，选择 **Amazon 简单电子邮件服务 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`：替换为您的 From (发件人) 电子邮件地址。运行此程序之前，您必须验证该地址。有关更多信息，请参阅 [Amazon SES 中已验证的身份](verify-addresses-and-domains.md)。
   + `RECIPIENT@EXAMPLE.COM`：替换为您的 To (收件人) 电子邮件地址。如果您的账户仍处于沙盒中，您还必须验证此地址，然后才能使用它。有关更多信息，请参阅 [请求生产访问权限（从 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**：访问 [http://php.net/downloads.php](http://php.net/downloads.php) 可获得 PHP。本教程需要 PHP 版本 5.5 或更高版本。安装 PHP 后，在环境变量中添加 PHP 的路径，这样就能通过任何命令提示符运行 PHP。本教程中的代码已使用 PHP 7.2.7 进行测试。
+ **安装 适用于 PHP 的 AWS SDK 版本 3**-有关下载和安装说明，请参阅[适用于 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`**：如果您要在发送此电子邮件时使用配置集，请将此值替换为配置集的名称。有关配置集的更多信息，请参阅[在 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”错误，请下载最新的 CA 服务包，如[适用于 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` 数组，将 `path_of_certs` 替换为您下载的 CA 捆绑的路径，然后重新运行程序。  

   ```
   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 开发人员指南*[》 适用于 Ruby 的 AWS SDK中的安装](https://docs.aws.amazon.com/sdk-for-ruby/latest/developer-guide/setup-install.html)。本教程中的示例代码已使用 2.9.36 版本的 适用于 Ruby 的 AWS SDK进行了测试。
+ **创建共享凭证文件** – 为了使此部分中的示例代码正常运行，您必须创建一个共享凭证文件。有关更多信息，请参阅 [创建共享凭证文件，以便在使用软件开发工具包通过 Amazon AWS 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 ]

本主题说明如何使用 [AWS SDK for Python (Boto)](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 证书**-您需要访问密钥 ID 和 AWS 私有 AWS 访问密钥才能使用软件开发工具包访问 Amazon SES。您可以通过 [的](https://console.aws.amazon.com/iam/home?#security_credential)安全凭证 AWS 管理控制台页面来查找您的凭证。有关凭证的更多信息，请参阅[Amazon SES 凭证的类型](send-email-concepts-credentials.md)。
+ **安装 Python —Python** 已在 thon.org/downloads/ 上[https://www.py线](https://www.python.org/downloads/)。本教程中的代码已使用 Python 2.7.6 和 Python 3.6.1 进行了测试。安装 Python 后，在环境变量中添加 Python 的路径，这样就能通过任何命令提示符运行 Python。
+ **安装 AWS SDK for Python (Boto)—有关**下载和安装说明，请参阅[AWS SDK for Python (Boto) 文档](https://boto3.readthedocs.io/en/latest/guide/quickstart.html#installation)。本教程中的示例代码已使用 1.4.4 版本的 SDK for Python 进行了测试。

**使用 SDK for 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.              "AWS SDK for Python (Boto)."
   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/'> AWS SDK for Python (Boto)</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. 登录收件人地址的电子邮件客户端。您将看到已发送的电子邮件。

------