

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# プログラミングで Amazon SES の SMTP インターフェイスを介して E メールを送信する
<a name="send-using-smtp-programmatically"></a>

Amazon SES の SMTP インターフェイスで E メールを送信するには、SMTP 対応のプログラミング言語、E メールサーバー、またはアプリケーションを使用できます。開始する前に、[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 インターフェイスにアクセスできます。SMTP 認証情報と Amazon SES SMTP ホスト名およびポート番号を使用して、プログラミング言語の 一般的な SMTP 機能によって E メールを送信します。

Amazon Elastic Compute Cloud (Amazon EC2) では、デフォルトでポート 25 経由での E メールトラフィックを制限しています。Amazon EC2 から SMTP エンドポイントを介して E メールを送信する際のタイムアウトを回避するには、これらの制限を解除するようリクエストすることができます。詳細については、[Amazon EC2インスタンスまたは AWS Lambda 関数からポート 25 の制限を削除するにはどうすればよいですか？」を参照してください。](https://aws.amazon.com/premiumsupport/knowledge-center/ec2-port-25-throttle/) AWS ナレッジセンターの 。

Java および PHP のこのセクションのコード例で、この問題を回避するためにポート 587 を使用します。

**注記**  
このチュートリアルでは、受信を確認できるように自分宛に E メールを送信します。さらに詳しい実験や負荷テストには、Amazon SES メールボックスシミュレーターを使用してください。メールボックスシミュレーターに送信される E メールは、送信クォータに加算されず、バウンス率や苦情率の計算にも含まれません。詳細については、[手動でメールボックスシミュレーターを使用する](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 から E メールを送信します。

以下の手順を実行する前に、[Amazon Simple Email Service を設定する](setting-up.md)に記載されている作業を完了します。

**Java で Amazon SES SMTP インターフェイスを使用して E メールを送信するには**

1. ウェブブラウザで、[JavaMail GitHub ページ](https://github.com/javaee/javamail/releases)に移動します。**[Assets]** の下で、**[javax.mail.jar]** を選択して、JavaMail の最新バージョンをダウンロードします。
**重要**  
このチュートリアルには、JavaMail バージョン 1.5 以降が必要です。これらの手順は、JavaMail バージョン 1.6.1 を使用してテスト済みです。

1. ウェブブラウザで [Jakarta Activation GitHub ページ](https://github.com/eclipse-ee4j/jaf/releases)に移動して、[[JavaBeans Activation Framework 1.2.1 Final Release]](https://github.com/eclipse-ee4j/jaf/releases/tag/1.2.1) の下で、**jakarta.activation.jar** をダウンロードします。

1. 次のステップを実行し、Eclipse でプロジェクトを作成します。

   1. Eclipse を起動します。

   1. Eclipse で、**ファイル**を選択し、**新規**、**Java Project** の順に選択します。

   1. **Create a Java Project** ダイアログボックスで、プロジェクト名を入力し、**次へ**を選択します。

   1. **Java Settings** ダイアログボックスの**ライブラリ**タブを選択します。

   1. **[Classpath]** を選択し、**[外部 JAR の追加]** ボタンを使用して、**javax.mail.jar** と **jakarta.activation.jar** の 2 つの外部 jar ファイルを追加します。

   1. **Add External JARs** を選択します。

   1. JavaMail をダウンロードした先のフォルダを参照します。`javax.mail.jar` ファイルを選択し、**開く**を選択します。

   1. **Java Settings** ダイアログボックスの**終了**を選択します。

1. Eclipse で、**Package Explorer**ウィンドウのプロジェクトを展開します。

1. プロジェクトの下の **src** ディレクトリを右クリックし、**新規**、**クラス**の順に選択します。

1. **New Java Class** ダイアログボックスの**名前**フィールドに `AmazonSESSample` と入力し、**終了**を選択します。

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** で、以下のメールアドレスを実際の値に置き換えます。
**重要**  
E メールアドレスでは、大文字と小文字は区別されます。検証したアドレスと完全に一致することを確認してください。
   + *sender@example.com* – 「送信元」メールアドレスに置き換えます。このアドレスを確認してから、プログラムを実行してください。詳細については、「[Amazon SES の検証済みID](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. (オプション) この E メール送信時に設定セットを使用する場合は、*ConfigSet* 変数の値をその設定セット名に変更します。設定セットの詳細については、[Amazon SES の設定セットの使用](using-configuration-sets.md)を参照ください。

1. **AmazonSESSample.java** を保存します。

1. プロジェクトを構築するため、**プロジェクト**、**プロジェクトの構築**の順に選択します。(このオプションが無効の場合、自動構築が有効になっている可能性があります。)

1. プログラムを開始して E メールを送信するため、**実行**を選択した後、もう一度**実行**を選択します。

1. 出力の確認 E メールの送信が正常に完了すると、コンソールに「*確認の E メールが送信されました*」と表示されます。送信が失敗した場合は、エラーメッセージが表示されます。

1. 受信者のアドレスの E メールクライアントにサインインします。送信した E メールメッセージを確認します。

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

この例では PHPMailer クラスを使用し、SMTP インターフェイスで Amazon SES を介して E メールを送信します。

以下の手順を実行する前に、[Amazon Simple Email Service を設定する](setting-up.md)のタスクを完了する必要があります。Amazon SES のセットアップに加えて、PHP で E メールを送信するには、次の前提条件を満たしている必要があります。

**前提条件:**
+ **PHP のインストール** – PHP は、[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
  ```

  前のコマンドで、*path/to/*を、Composer をインストールしたパスに置き換えます。

**PHP で Amazon SES の SMTP インターフェイスを使用して E メールを送信するには**

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 で検証した E メールアドレスに置き換えます。詳細については、「[検証済みID](verify-addresses-and-domains.md)」を参照してください。Amazon SES では、E メールアドレスの大文字と小文字が区別されます。検証したアドレスと完全に一致するアドレスを入力してください。
   + *recipient@example.com* – 送信先アドレスに置き換えます。アカウントがサンドボックスにまだある場合は、このアドレスを使用前に確認する必要があります。詳細については、「[本稼働アクセスのリクエスト (Amazon SES サンドボックスからの移行)](request-production-access.md)」を参照してください。検証したアドレスと完全に一致するアドレスを入力してください。
   + *smtp\$1username* – SMTP ユーザー名の認証情報に置き換えます。これは、Amazon SES コンソールの [[SMTP 設定]](https://console.aws.amazon.com/ses/home?#smtp-settings:) ページで取得したものです。これは AWS アクセスキー ID とは**異なり**ます。SMTP ユーザー名の認証情報は 20 文字の文字と数字の並びであり、意味のある名前ではありません。
   + *smtp\$1password* – パスワードを取得するために ``fetchSMTPPasswordFromSecureStorage`` を実装します。
   + (オプション) *ConfigSet* – この E メール送信時に設定セットを使用する場合は、この値を設定セット名に置き換えます。設定セットの詳細については、[Amazon SES の設定セットの使用](using-configuration-sets.md)を参照ください。
   + (オプション) *email-smtp.us-west-2.amazonaws.com* – 米国西部 (オレゴン) 以外のリージョンの Amazon SES SMTP エンドポイントを使用する場合は、この値を使用するリージョンの Amazon SES SMTP エンドポイントに置き換えます。 AWS リージョン Amazon SES が利用可能な の 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. 出力の確認 E メールの送信が正常に完了すると、コンソールに「*確認の E メールが送信されました*」と表示されます。送信が失敗した場合は、エラーメッセージが表示されます。

1. 受信者のアドレスの E メールクライアントにサインインします。送信したメッセージを確認します。

------