

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

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

------