

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

# 通过 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) 中的任务。

**将 Amazon SES SMTP 接口与 Java 结合使用来发送电子邮件**

1. 在 Web 浏览器中，转到该[JavaMail GitHub 页面](https://github.com/javaee/javamail/releases)。在 “**资产**” 下，选择 **javax.mail.jar** 以下载最新版本的。 JavaMail
**重要**  
本教程需要 JavaMail 版本 1.5 或更高版本。这些程序已使用 JavaMail 版本 1.6.1 进行了测试。

1. **在网络浏览器中，进入[雅加达激活 GitHub 页面，在 “激JavaBeans 活](https://github.com/eclipse-ee4j/jaf/releases)[框架 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**。

   1. 在 **Create a Java Project** 对话框中，键入项目名称，然后选择 **Next**。

   1. 在 **Java Settings** 对话框中，选择 **Libraries** 选项卡。

   1. ****选择 **Classpath**，然后使用添加外部按钮添加两个外部 jar 文件 j **avax.mail.jar 和 jakarta.activation.jar。** JARs****

   1. 选择 “**添加外部**” JARs。

   1. 浏览到您下载的文件夹 JavaMail。选择文件 `javax.mail.jar`，然后选择 **Open**。

   1. 在 **Java Settings** 对话框中，选择 **Finish**。

1. 在 Eclipse 中的 **Package Explorer** 窗口中，展开您的项目。

1. 在您的项目下，右键单击 **src** 目录，选择 **New**，然后选择 **Class**。

1. 在 **New Java Class** 对话框中的 **Name** 字段中，键入 `AmazonSESSample`，然后选择 **Finish**。

1. 将 **Amazon SESSample .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. 在 **Amazon SESSample .java** 中，用您自己的值替换以下电子邮件地址：
**重要**  
电子邮件地址区分大小写。请确保此处的地址与经验证的地址完全相同。
   + *sender@example.com*— 替换为您的 “发件人” 电子邮件地址。运行此程序之前，您必须验证该地址。有关更多信息，请参阅 [Amazon SES 中已验证的身份](verify-addresses-and-domains.md)。
   + *recipient@example.com*— 替换为您的 “收件人” 电子邮件地址。如果您的账户仍处于沙盒中，您还必须验证此地址，然后才能使用它。有关更多信息，请参阅 [请求生产访问权限（从 Amazon SES 沙盒中移出）](request-production-access.md)。

1. 在 **Amazon SESSample .java** 中，将以下内容替换为你自己的值：
   + *smtp\$1username*— 替换为您的 SMTP 用户名凭证。请注意，您的 SMTP 用户名凭证是一个 20 个字符的字母数字字符串，而不是可识别的名称。
   + *smtp\$1password*— ``fetchSMTPPasswordFromSecureStorage`` 实现获取密码。

1. （可选）如果您想在以 AWS 区域 外的地方使用 Amazon SES SMTP 终端节点*email-smtp.us-west-2.amazonaws.com*，请`HOST`将变量的值更改为您要使用的终端节点。有关已推出 Amazon SES 的区域的列表，请参阅《AWS 一般参考》**中的 [Amazon Simple Email Service（Amazon SES）](https://docs.aws.amazon.com/general/latest/gr/rande.html#ses_region)。

1. （可选）如果要在发送此电子邮件时使用配置集，请将变量 *ConfigSet* 的值更改为配置集的名称。有关配置集的更多信息，请参阅[在 SES 中使用配置集](using-configuration-sets.md)。

1. 保存 **Amazon SESSample .java。**

1. 要构建项目，请选择 **Project**，然后选择 **Build Project**。（如果禁用此选项，则您可能已启用自动构建。）

1. 要开始程序和发送电子邮件，请选择 **Run**，然后再次选择 **Run**。

1. 检查输出。如果已成功发送电子邮件，则控制台会显示“*Email sent\$1*”。否则，将显示一条错误消息。

1. 登录收件人地址的电子邮件客户端。您将看到已发送的电子邮件。

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

此示例使用该 PHPMailer 类通过 SMTP 接口通过 Amazon SES 发送电子邮件。

执行以下步骤之前，必须完成 [设置 Amazon Simple Email Service](setting-up.md) 中的任务。除了设置 Amazon SES，您还必须完成以下先决条件才能使用 PHP 发送电子邮件：

**先决条件：**
+ **安装 PHP**：访问 [http://php.net/downloads.php](https://php.net/downloads.php) 可获得 PHP。安装 PHP 后，在环境变量中添加 PHP 的路径，这样就能通过任何命令提示符运行 PHP。
+ **安装 Composer 依赖项管理器** — 安装 Composer 依赖项管理器后，您可以下载并安装该 PHPMailer 类及其依赖项。要安装 Composer，请按照 pos [https://getcomer.org/downlo](https://getcomposer.org/download) ad 上的安装说明进行操作。
+ **安装该 PHPMailer 类** — 安装 Composer 后，运行以下命令进行安装 PHPMailer：

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

  在前面的命令中，*path/to/*替换为安装 Composer 的路径。

**将 Amazon SES SMTP 接口与 PHP 结合使用来发送电子邮件**

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:) 用户名证书。这与您的 ** 访问密钥 ID **不同 AWS 。请注意，您的 SMTP 用户名凭证是一个 20 个字符的字母数字字符串，而不是可识别的名称。
   + *smtp\$1password*— ``fetchSMTPPasswordFromSecureStorage`` 实现获取密码。
   + （可选）*ConfigSet*— 如果您想在发送此电子邮件时使用配置集，请将此值替换为配置集的名称。有关配置集的更多信息，请参阅[在 SES 中使用配置集](using-configuration-sets.md)。
   + （可选）*email-smtp.us-west-2.amazonaws.com*— 如果您想在美国西部（俄勒冈）以外的地区使用 Amazon SES SMTP 终端节点，请将其替换为您要使用的区域中的 Amazon SES SMTP 终端节点。有关可用 Amazon SES 的 SMTP 终端节点 URLs 列表，请参阅中的 AWS 区域 [亚马逊简单电子邮件服务 (Amazon SES) Service](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. 检查输出。如果已成功发送电子邮件，则控制台会显示“*Email sent\$1*”。否则，将显示一条错误消息。

1. 登录收件人地址的电子邮件客户端。您将看到已发送的电子邮件。

------