プログラミングで Amazon SES の SMTP インターフェイスを介して E メールを送信する - Amazon Simple Email Service

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

プログラミングで Amazon SES の SMTP インターフェイスを介して E メールを送信する

Amazon SES の SMTP インターフェイスで E メールを送信するには、SMTP 対応のプログラミング言語、E メールサーバー、またはアプリケーションを使用できます。開始する前に、Amazon Simple Email Service を設定するのタスクを完了します。また、以下の詳細を取得する必要があります。

コードの例

SMTP 対応のプログラミング言語を使用して、Amazon SES の SMTP インターフェイスにアクセスできます。SMTP 認証情報と Amazon SES SMTP ホスト名およびポート番号を使用して、プログラミング言語の 一般的な SMTP 機能によって E メールを送信します。

Amazon Elastic Compute Cloud (Amazon EC2) では、デフォルトでポート 25 経由での E メールトラフィックを制限しています。Amazon EC2 から SMTP エンドポイントを介して E メールを送信する際のタイムアウトを回避するには、これらの制限を解除するようリクエストすることができます。詳細については、「 AWS ナレッジセンター」のAmazon EC2 インスタンスまたは AWS Lambda 関数からポート 25 の制限を削除する方法」を参照してください。

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

注記

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

プログラミング言語を選択して、その言語の例を表示します。

警告

Amazon SES では、静的認証情報の使用はお勧めしません。ソースコードからハードコードされた認証情報を削除してセキュリティ体制を改善する方法については、「AWS Secrets Manager」を参照してください。このチュートリアルは、本番環境以外の環境で Amazon SES SMTP インターフェイスをテストする目的でのみ提供されています。

Java

この例では、Eclipse IDEJavaMail APIを使用して、SMTP インターフェイスで Amazon SES から E メールを送信します。

以下の手順を実行する前に、Amazon Simple Email Service を設定するに記載されている作業を完了します。

Java で Amazon SES SMTP インターフェイスを使用して E メールを送信するには
  1. ウェブブラウザで、JavaMail GitHub ページに移動します。[Assets] の下で、[javax.mail.jar] を選択して、JavaMail の最新バージョンをダウンロードします。

    重要

    このチュートリアルには、JavaMail バージョン 1.5 以降が必要です。これらの手順は、JavaMail バージョン 1.6.1 を使用してテスト済みです。

  2. ウェブブラウザで Jakarta Activation GitHub ページに移動して、[JavaBeans Activation Framework 1.2.1 Final Release] の下で、jakarta.activation.jar をダウンロードします。

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

    1. Eclipse を起動します。

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

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

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

    5. [Classpath] を選択し、[Add External JARs] ボタンを使用して、javax.mail.jarjakarta.activation.jar の 2 つの外部 jar ファイルを追加します。

    6. Add External JARs を選択します。

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

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

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

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

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

  7. AmazonSESSample.java のコンテンツ全体を以下のコードに置き換えます。

    import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class AmazonSESSample { // Replace sender@example.com with your "From" address. // This address must be verified. static final String FROM = "sender@example.com"; static final String FROMNAME = "Sender Name"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. static final String TO = "recipient@example.com"; // Replace smtp_username with your Amazon SES SMTP user name. static final String SMTP_USERNAME = "smtp_username"; // The name of the Configuration Set to use for this message. // If you comment out or remove this variable, you will also need to // comment out or remove the header below. static final String CONFIGSET = "ConfigSet"; // Amazon SES SMTP host name. This example uses the US West (Oregon) region. // See https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html#region-endpoints // for more information. static final String HOST = "email-smtp.us-west-2.amazonaws.com"; // The port you will connect to on the Amazon SES SMTP endpoint. static final int PORT = 587; static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)"; static final String BODY = String.join( System.getProperty("line.separator"), "<h1>Amazon SES SMTP Email Test</h1>", "<p>This email was sent with Amazon SES using the ", "<a href='https://github.com/javaee/javamail'>Javamail Package</a>", " for <a href='https://www.java.com'>Java</a>." ); public static void main(String[] args) throws Exception { // Create a Properties object to contain connection configuration information. Properties props = System.getProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", PORT); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); // Create a Session object to represent a mail session with the specified properties. Session session = Session.getDefaultInstance(props); // Create a message with the specified information. MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(FROM,FROMNAME)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO)); msg.setSubject(SUBJECT); msg.setContent(BODY,"text/html"); // Add a configuration set header. Comment or delete the // next line if you are not using a configuration set msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGSET); // Create a transport. Transport transport = session.getTransport(); // Get the password String SMTP_PASSWORD = fetchSMTPPasswordFromSecureStorage(); // Send the message. try { System.out.println("Sending..."); // Connect to Amazon SES using the SMTP username and password you specified above. transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD); // Send the email. transport.sendMessage(msg, msg.getAllRecipients()); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent."); System.out.println("Error message: " + ex.getMessage()); } finally { // Close and terminate the connection. transport.close(); } } static String fetchSMTPPasswordFromSecureStorage() { /* IMPLEMENT THIS METHOD */ // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/ } }
  8. AmazonSESSample.java で、以下のメールアドレスを実際の値に置き換えます。

    重要

    E メールアドレスでは、大文字と小文字は区別されます。検証したアドレスと完全に一致することを確認してください。

    • sender@example.com – 「送信元」メールアドレスに置き換えます。このアドレスを確認してから、プログラムを実行してください。詳細については、「Amazon SES の検証済みID」を参照してください。

    • recipient@example.com – 「送信先」メールアドレスに置き換えます。アカウントがサンドボックスにまだある場合は、このアドレスを使用前に確認する必要があります。詳細については、「本稼働アクセスのリクエスト (Amazon SES サンドボックスからの移行)」を参照してください。

  9. AmazonSESSample.java で、以下を実際の値に置き換えます。

    • smtp_username – SMTP ユーザー名の認証情報に置き換えます。SMTP ユーザー名の認証情報は 20 文字の文字と数字の並びであり、意味のある名前ではありません。

    • smtp_password – パスワードを取得するために `fetchSMTPPasswordFromSecureStorage` を実装します。

  10. (オプション) email-smtp.us-west-2.amazonaws.com 以外の AWS リージョン Amazon SES SMTP エンドポイントを使用する場合は、HOST 変数の値を実際に使用するエンドポイントに変更します。Amazon SES を使用できるリージョンのリストについては、「AWS 全般のリファレンス」の「Amazon Simple Email Service (Amazon SES)」を参照してください。

  11. (オプション) この E メール送信時に設定セットを使用する場合は、ConfigSet 変数の値をその設定セット名に変更します。設定セットの詳細については、Amazon SES の設定セットの使用を参照ください。

  12. AmazonSESSample.java を保存します。

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

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

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

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

PHP

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

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

前提条件:
  • PHP のインストール – PHP は、http://php.net/downloads.php で入手できます。PHP をインストールした後、コマンドプロンプトから PHP を実行できるように環境変数に PHP のパスを追加します。

  • Composer 依存関係管理システムのインストール – Composer 依存関係管理システムのインストール後、PHPMailer クラスと依存関係をダウンロードしてインストールできます。Composer をインストールするには、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 という名前のファイルを作成します。テキストエディタでファイルを開き、次のコードを貼り付けます。

    <?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // If necessary, modify the path in the require statement below to refer to the // location of your Composer autoload.php file. require 'vendor/autoload.php'; // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. $sender = 'sender@example.com'; $senderName = 'Sender Name'; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. $recipient = 'recipient@example.com'; // Replace smtp_username with your Amazon SES SMTP user name. $usernameSmtp = 'smtp_username'; // Specify a configuration set. If you do not want to use a configuration // set, comment or remove the next line. $configurationSet = 'ConfigSet'; // If you're using Amazon SES in a region other than US West (Oregon), // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP // endpoint in the appropriate region. $host = 'email-smtp.us-west-2.amazonaws.com'; $port = 587; // The subject line of the email $subject = 'Amazon SES test (SMTP interface accessed using PHP)'; // The plain-text body of the email $bodyText = "Email Test\r\nThis email was sent through the Amazon SES SMTP interface using the PHPMailer class."; // The HTML-formatted body of the email $bodyHtml = '<h1>Email Test</h1> <p>This email was sent through the <a href="https://aws.amazon.com/ses">Amazon SES</a> SMTP interface using the <a href="https://github.com/PHPMailer/PHPMailer"> PHPMailer</a> class.</p>'; $mail = new PHPMailer(true); try { // Specify the SMTP settings. $mail->isSMTP(); $mail->setFrom($sender, $senderName); $mail->Username = $usernameSmtp; $mail->Password = fetchSMTPPasswordFromSecureStorage(); $mail->Host = $host; $mail->Port = $port; $mail->SMTPAuth = true; $mail->SMTPSecure = 'tls'; $mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configurationSet); // Specify the message recipients. $mail->addAddress($recipient); // You can also add CC, BCC, and additional To recipients here. // Specify the content of the message. $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $bodyHtml; $mail->AltBody = $bodyText; $mail->Send(); echo "Email sent!" , PHP_EOL; } catch (phpmailerException $e) { echo "An error occurred. {$e->errorMessage()}", PHP_EOL; //Catch errors from PHPMailer. } catch (Exception $e) { echo "Email not sent. {$mail->ErrorInfo}", PHP_EOL; //Catch errors from Amazon SES. } function fetchSMTPPasswordFromSecureStorage() { /* IMPLEMENT THIS METHOD */ // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/ } ?>
  2. amazon-ses-smtp-sample.php で、以下を実際の値に置き換えます。

    • sender@example.com – Amazon SES で検証した E メールアドレスに置き換えます。詳細については、「検証済みID」を参照してください。Amazon SES では、E メールアドレスの大文字と小文字が区別されます。検証したアドレスと完全に一致するアドレスを入力してください。

    • recipient@example.com – 送信先アドレスに置き換えます。アカウントがサンドボックスにまだある場合は、このアドレスを使用前に確認する必要があります。詳細については、「本稼働アクセスのリクエスト (Amazon SES サンドボックスからの移行)」を参照してください。検証したアドレスと完全に一致するアドレスを入力してください。

    • smtp_username – SMTP ユーザー名の認証情報に置き換えます。これは、Amazon SES コンソールの [SMTP 設定] ページで取得したものです。これは AWS アクセスキー ID とは異なります。SMTP ユーザー名の認証情報は 20 文字の文字と数字の並びであり、意味のある名前ではありません。

    • smtp_password – パスワードを取得するために `fetchSMTPPasswordFromSecureStorage` を実装します。

    • (オプション) ConfigSet – この E メール送信時に設定セットを使用する場合は、この値を設定セット名に置き換えます。設定セットの詳細については、Amazon SES の設定セットの使用を参照ください。

    • (オプション) email-smtp.us-west-2.amazonaws.com – 米国西部 (オレゴン) 以外のリージョンの Amazon SES SMTP エンドポイントを使用する場合は、この値を使用するリージョンの Amazon SES SMTP エンドポイントに置き換えます。 AWS リージョン Amazon SES が利用可能な の SMTP エンドポイント URLs「」の「Amazon Simple Email Service (Amazon SES)」を参照してくださいAWS 全般のリファレンス

  3. amazon-ses-smtp-sample.php を保存します。

  4. このプログラムを実行するには、amazon-ses-smtp-sample.php と同じディレクトリでコマンドプロンプトを開いて、php amazon-ses-smtp-sample.php と入力します。

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

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