通过 Amazon SES SMTP 接口以编程方式来发送电子邮件 - Amazon Simple Email Service

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

通过 Amazon SES SMTP 接口以编程方式来发送电子邮件

要使用 Amazon SES SMTP 接口来发送电子邮件,您可以使用支持 SMTP 的编程语言、电子邮件服务器或应用程序。在开启之前,请完成设置 Amazon Simple Email Service中的任务。建议您了解以下信息:

代码示例

您可以使用支持 SMTP 的编程语言来访问 Amazon SES SMTP 接口。您可以提供 Amazon SES SMTP 主机名和端口号以及您的 SMTP 凭证,然后使用编程语言的一般 SMTP 函数来发送电子邮件。

默认情况下,Amazon Elastic Compute Cloud(Amazon EC2)会限制端口 25 上的电子邮件流量。为了避免在通过 SMTP 端点从 Amazon EC2 发送电子邮件时发生超时,您可以请求移除这些限制。有关更多信息,请参阅如何从我的 Amazon EC2 实例或 AWS Lambda 函数中移除对端口 25 的限制? 在 AWS 知识中心中。

本节中的 Java 和 PHP 代码示例使用端口 587 来避免此问题。

注意

在这些教程中,您将向自己发送电子邮件,以便检查是否收到了该电子邮件。如需进一步试验或进行负载测试,请使用 Amazon SES 邮箱模拟器。您发送到邮箱模拟器的电子邮件不会计入您的发送配额或您的退信率和投诉率。有关更多信息,请参阅 手动使用邮箱模拟器

选择一种编程语言以查看该语言的示例:

警告

Amazon SES 不建议使用静态证书。请参阅 AWS Secrets Manager,了解如何通过从源代码中删除硬编码凭据来改善您的安全状况。本教程仅用于在非生产环境中测试 Amazon SES SMTP 接口。

Java

此示例使用 Eclipse IDEJavaMail API 使用 SMTP 接口通过 Amazon SES 发送电子邮件。

执行以下步骤之前,请完成 设置 Amazon Simple Email Service 中的任务。

将 Amazon SES SMTP 接口与 Java 结合使用来发送电子邮件
  1. 在 Web 浏览器中,转到该JavaMail GitHub 页面。在 “资产” 下,选择 javax.mail.jar 以下载最新版本的。 JavaMail

    重要

    本教程需要 JavaMail 版本 1.5 或更高版本。这些程序已使用 JavaMail 版本 1.6.1 进行了测试。

  2. 在网络浏览器中,进入雅加达激活 GitHub 页面,在 “激JavaBeans 活框架 1.2.1 最终版本” 下,下载 jakarta.activation.jar

  3. 通过执行以下步骤在 Eclipse 中创建项目:

    1. 启动 Eclipse。

    2. 在 Eclipse 中,依次选择 FileNewJava Project

    3. Create a Java Project 对话框中,键入项目名称,然后选择 Next

    4. Java Settings 对话框中,选择 Libraries 选项卡。

    5. 选择 Classpath,然后使用 “添加外部 JAR” 按钮添加两个外部 jar 文件 j avax.mail.jar 和 jakarta.activation.jar。

    6. 选择 Add External JARs

    7. 浏览到您下载的文件夹 JavaMail。选择文件 javax.mail.jar,然后选择 Open

    8. Java Settings 对话框中,选择 Finish

  4. 在 Eclipse 中的 Package Explorer 窗口中,展开您的项目。

  5. 在您的项目下,右键单击 src 目录,选择 New,然后选择 Class

  6. New Java Class 对话框中的 Name 字段中,键入 AmazonSESSample,然后选择 Finish

  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 中,将以下电子邮件地址替换为您自己的值:

    重要

    电子邮件地址区分大小写。请确保此处的地址与经验证的地址完全相同。

    • sender@example.com — 替换为你的 “发件人” 电子邮件地址。运行此程序之前,您必须验证该地址。有关更多信息,请参阅 Amazon SES 中已验证的身份

    • 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. (可选)如果要在发送此电子邮件时使用配置集,请ConfigSet将变量的值更改为配置集的名称。有关配置集的更多信息,请参阅在 SES 中使用配置集

  12. 保存 AmazonSESSample.java

  13. 要构建项目,请选择 Project,然后选择 Build Project。(如果禁用此选项,则您可能已启用自动构建。)

  14. 要开始程序和发送电子邮件,请选择 Run,然后再次选择 Run

  15. 检查输出。如果电子邮件已成功发送,控制台将显示 “电子邮件已发送!” 否则,它会显示一条错误消息。

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

PHP

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

执行以下步骤之前,必须完成 设置 Amazon Simple Email Service 中的任务。除了设置 Amazon SES,您还必须完成以下先决条件才能使用 PHP 发送电子邮件:

先决条件:
  • 安装 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 的路径。

将 Amazon SES SMTP 接口与 PHP 结合使用来发送电子邮件
  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 验证的电子邮件地址。有关更多信息,请参阅 已验证的身份。Amazon SES 中的电子邮件地址区分大小写。请确保您输入的地址与经验证的地址完全相同。

    • recipient@example.com — 替换为收件人的地址。如果您的账户仍处于沙盒中,您还必须验证此地址,然后才能使用它。有关更多信息,请参阅 申请生产访问权限(移出 Amazon SES 沙箱)。请确保您输入的地址与经验证的地址完全相同。

    • smtp_usern ame — 替换为您从 Amazon SES 控制台的 SMTP 设置页面获得的 SMTP 用户名凭证。这与您的 访问密钥 ID 不同 AWS 。请注意,您的 SMTP 用户名凭证是一个 20 个字符的字母数字字符串,而不是可识别的名称。

    • smtp_password — 实现`fetchSMTPPasswordFromSecureStorage`以获取密码

    • (可选)ConfigSet— 如果您想在发送此电子邮件时使用配置集,请将此值替换为配置集的名称。有关配置集的更多信息,请参阅在 SES 中使用配置集

    • (可选)email-smtp.us-west-2.amazonaws.com — 如果您想在美国西部(俄勒冈)以外的地区使用 Amazon SES SMTP 终端节点,请将其替换为您要使用的区域中的 Amazon SES SMTP 终端节点。有关可用 Amazon SES 的 SMTP 终端节点网址列表,请参阅中的 AWS 区域 亚马逊简单电子邮件服务 (Amazon SES) ServiceAWS 一般参考

  3. 保存 amazon-ses-smtp-sample.php。

  4. 要运行该程序,请在与 amazon-ses-smtp-sample.php 相同的目录中打开命令提示符,然后键入php amazon-ses-smtp-sample.php

  5. 检查输出。如果电子邮件已成功发送,控制台将显示 “电子邮件已发送!” 否则,它会显示一条错误消息。

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