プログラミングで 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 IDE と API を使用して、SMTP インターフェイスを使用して Amazon SES 経由で E メールを送信します。 JavaMail

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

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

    重要

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

  2. ウェブブラウザで Jakarta アクティベーション GitHub ページ に移動しJavaBeans アクティベーションフレームワーク 1.2.1 最終リリース jakarta.activation.jar をダウンロードします。

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

    1. Eclipse を起動します。

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

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

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

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

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

  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 – を、Amazon SES コンソールの SMTP 設定ページから取得した SMTP ユーザー名の認証情報に置き換えます。 Amazon SES これは 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 メールクライアントにサインインします。送信したメッセージを確認します。