SES使用 Amazon 通过亚马逊发送电子邮件 AWS SDK - Amazon Simple Email Service

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

SES使用 Amazon 通过亚马逊发送电子邮件 AWS SDK

你可以使用 AWS SDK通过 Amazon 发送电子邮件SES。 AWS SDKs适用于多种编程语言。有关更多信息,请参阅用于 Amazon Web Services 的工具

先决条件

要完成下一节中的任何代码示例,必须完成以下先决条件:

代码示例

重要

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

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

    以下过程向您展示了如何SES使用 Visual Studio 通过亚马逊发送电子邮件以及 AWS SDK for .NET.

    已使用以下组件测试此解决方案:

    • Microsoft Visual Studio Community 2017 版本 15.4.0。

    • 微软。 NET框架版本 4.6.1。

    • AWSSDK.Core 软件包(版本 3.3.19),使用安装。 NuGet

    • 的 AWSSDK。 SimpleEmail 软件包(版本 3.3.6.1),使用安装。 NuGet

    在开始前,请执行以下任务:
    要使用发送电子邮件 AWS SDK for .NET
    1. 通过执行以下步骤创建新项目:

      1. 启动 Visual Studio。

      2. File 菜单上,依次选择 NewProject

      3. New Project 窗口上的左侧面板中,展开 Installed,然后展开 Visual C#

      4. 在右侧面板中,选择控制台应用程序 (. NET框架)

      5. 对于名称,键入 AmazonSESSample,然后选择 确定

    2. 完成以下步骤 NuGet ,使用在您的解决方案中SES包含 Amazon 软件包:

      1. 在 “解决方案资源管理器” 窗格中,右键单击您的项目,然后选择 “管理 NuGet 包”。

      2. NuGet:A mazonSESSample 选项卡上,选择浏览

      3. 在搜索框中,键入 AWSSDK.SimpleEmail

      4. 选择AWSSDK。 SimpleEmail软件包,然后选择 “安装”。

      5. Preview Changes 窗口中,选择 OK

    3. Program.cs 选项卡上,粘贴以下代码:

      using Amazon; using System; using System.Collections.Generic; using Amazon.SimpleEmail; using Amazon.SimpleEmail.Model; namespace AmazonSESSample { class Program { // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. static readonly string senderAddress = "sender@example.com"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. static readonly string receiverAddress = "recipient@example.com"; // The configuration set to use for this email. If you do not want to use a // configuration set, comment out the following property and the // ConfigurationSetName = configSet argument below. static readonly string configSet = "ConfigSet"; // The subject line for the email. static readonly string subject = "Amazon SES test (AWS SDK for .NET)"; // The email body for recipients with non-HTML email clients. static readonly string textBody = "Amazon SES Test (.NET)\r\n" + "This email was sent through Amazon SES " + "using the AWS SDK for .NET."; // The HTML body of the email. static readonly string htmlBody = @"<html> <head></head> <body> <h1>Amazon SES Test (AWS SDK for .NET)</h1> <p>This email was sent with <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the <a href='https://aws.amazon.com/sdk-for-net/'> AWS SDK for .NET</a>.</p> </body> </html>"; static void Main(string[] args) { // Replace USWest2 with the AWS Region you're using for Amazon SES. // Acceptable values are EUWest1, USEast1, and USWest2. using (var client = new AmazonSimpleEmailServiceClient(RegionEndpoint.USWest2)) { var sendRequest = new SendEmailRequest { Source = senderAddress, Destination = new Destination { ToAddresses = new List<string> { receiverAddress } }, Message = new Message { Subject = new Content(subject), Body = new Body { Html = new Content { Charset = "UTF-8", Data = htmlBody }, Text = new Content { Charset = "UTF-8", Data = textBody } } }, // If you are not using a configuration set, comment // or remove the following line ConfigurationSetName = configSet }; try { Console.WriteLine("Sending email using Amazon SES..."); var response = client.SendEmail(sendRequest); Console.WriteLine("The email was sent successfully."); } catch (Exception ex) { Console.WriteLine("The email was not sent."); Console.WriteLine("Error message: " + ex.Message); } } Console.Write("Press any key to continue..."); Console.ReadKey(); } } }
    4. 在代码编辑器中,执行下列操作:

      • Replace(替换) sender@example.com 使用 “发件人:” 电子邮件地址。必须验证此地址。有关更多信息,请参阅 Amazon SES 中已验证的身份

      • Replace(替换) recipient@example.com 带有 “收件人:” 地址。如果您的账户仍处于沙盒中,则还必须验证此地址。

      • Replace(替换) ConfigSet 设置为发送此电子邮件时使用的配置名称。

      • Replace(替换) USWest2 用名字命名 AWS 区域 您用于通过 Amazon 发送电子邮件的终端节点SES。有关提供亚马逊SES服务的地区列表,请参阅中的亚马逊简单电子邮件服务 (AmazonSES) AWS 一般参考.

      完成后,保存 Program.cs

    5. 通过完成以下步骤来生成并运行应用程序:

      1. Build 菜单上,选择 Build Solution

      2. Debug 菜单上,选择 Start Debugging。此时显示一个控制台窗口。

    6. 检查控制台的输出。如果已成功发送电子邮件,则控制台会显示“The email was sent successfully.

    7. 如果已成功发送电子邮件,请登录收件人地址的电子邮件客户端。您将看到已发送的电子邮件。

    Java

    以下过程向您展示了如何使用IDE适用于 Java EE 开发人员的 Eclips e 以及 AWS Toolkit for Eclipse创建 AWS SDK投影并修改 Java 代码以通过 Amazon 发送电子邮件SES。

    在开始前,请执行以下任务:
    要使用发送电子邮件 AWS SDK for Java
    1. 创建一个 AWS 通过执行以下步骤在 Eclipse 中执行 Java 项目:

      1. 启动 Eclipse。

      2. File 菜单上,选择 New,然后选择 Other。在 “新建” 窗口中,展开 AWS文件夹,然后选择 AWS Java 项目

      3. 在新版本中 AWS Java 项目对话框中,执行以下操作:

        1. 对于 Project name,键入项目的名称。

        2. 下AWS SDK for Java 示例,选择 Amazon 简单电子邮件服务 JavaMail 示例

        3. 选择完成

    2. 在 Eclipse 中的 Package Explorer 窗格中,展开您的项目。

    3. 在您的项目下,展开 src/main/java 文件夹,展开 com.amazon.aws.samples 文件夹,然后双击 AmazonSESSample.java

    4. AmazonSESSample.java 的整个内容替换为以下代码:

      package com.amazonaws.samples; import java.io.IOException; import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder; import com.amazonaws.services.simpleemail.model.Body; import com.amazonaws.services.simpleemail.model.Content; import com.amazonaws.services.simpleemail.model.Destination; import com.amazonaws.services.simpleemail.model.Message; import com.amazonaws.services.simpleemail.model.SendEmailRequest; public class AmazonSESSample { // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. static final String FROM = "sender@example.com"; // 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"; // The configuration set to use for this email. If you do not want to use a // configuration set, comment the following variable and the // .withConfigurationSetName(CONFIGSET); argument below. static final String CONFIGSET = "ConfigSet"; // The subject line for the email. static final String SUBJECT = "Amazon SES test (AWS SDK for Java)"; // The HTML body for the email. static final String HTMLBODY = "<h1>Amazon SES test (AWS SDK for Java)</h1>" + "<p>This email was sent with <a href='https://aws.amazon.com/ses/'>" + "Amazon SES</a> using the <a href='https://aws.amazon.com/sdk-for-java/'>" + "AWS SDK for Java</a>"; // The email body for recipients with non-HTML email clients. static final String TEXTBODY = "This email was sent through Amazon SES " + "using the AWS SDK for Java."; public static void main(String[] args) throws IOException { try { AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard() // Replace US_WEST_2 with the AWS Region you're using for // Amazon SES. .withRegion(Regions.US_WEST_2).build(); SendEmailRequest request = new SendEmailRequest() .withDestination( new Destination().withToAddresses(TO)) .withMessage(new Message() .withBody(new Body() .withHtml(new Content() .withCharset("UTF-8").withData(HTMLBODY)) .withText(new Content() .withCharset("UTF-8").withData(TEXTBODY))) .withSubject(new Content() .withCharset("UTF-8").withData(SUBJECT))) .withSource(FROM) // Comment or remove the next line if you are not using a // configuration set .withConfigurationSetName(CONFIGSET); client.sendEmail(request); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent. Error message: " + ex.getMessage()); } } }
    5. AmazonSESSample.java 中,将以下内容替换为您自己的值:

      重要

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

      • SENDER@EXAMPLE.COM – 替换为您的 From (发件人) 电子邮件地址。运行此程序之前,您必须验证该地址。有关更多信息,请参阅 Amazon SES 中已验证的身份

      • RECIPIENT@EXAMPLE.COM – 替换为您的 To (收件人) 电子邮件地址。如果您的账户仍处于沙盒中,您还必须验证此地址,然后才能使用它。有关更多信息,请参阅 申请生产访问权限(移出 Amazon SES 沙箱)

      • (可选)us-west-2— 如果您想在美国西部(俄勒冈)以外的地区使用 AmazonSES,请将其替换为您要使用的区域。有关提供亚马逊SES服务的地区列表,请参阅《亚马逊简单电子邮件服务》(AmazonSES) AWS 一般参考.

    6. 保存 AmazonSESSample.java

    7. 要构建项目,请选择 Project,然后选择 Build Project

      注意

      如果禁用此选项,则可能启用自动构建;如果是这样,请跳过此步骤。

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

    9. 在 Eclipse 中查看控制台窗格的输出。如果已成功发送电子邮件,则控制台会显示“Email sent!”,否则将显示一条错误消息。

    10. 如果已成功发送电子邮件,请登录收件人地址的电子邮件客户端。您将看到已发送的电子邮件。

    PHP

    本主题介绍如何使用 AWS SDK for PHP通过 Amazon 发送电子邮件SES。

    在开始前,请执行以下任务:
    • 安装 PHP — PHP 可通过 http://php.net/downloads.php 获得。本教程需要PHP版本 5.5 或更高版本。安装后PHP,在环境变量PHP中添加路径,这样您就可以在任何命令提示符下运行PHP。本教程中的代码已使用 PHP 7.2.7 进行了测试。

    • 安装 AWS SDK for PHP 版本 3 -有关下载和安装说明,请参阅 AWS SDK for PHP 文档。本教程中的代码已使用的 3.64.13 版本进行了测试。SDK

    要通过 Amazon 发送电子邮件,SES请使用 AWS SDK for PHP
    1. 在文本编辑器中,创建一个名为 amazon-ses-sample.php 的文件。粘贴以下代码:

      <?php // 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'; use Aws\Ses\SesClient; use Aws\Exception\AwsException; // Create an SesClient. Change the value of the region parameter if you're // using an AWS Region other than US West (Oregon). Change the value of the // profile parameter if you want to use a profile in your credentials file // other than the default. $SesClient = new SesClient([ 'profile' => 'default', 'version' => '2010-12-01', 'region' => 'us-west-2' ]); // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. $sender_email = 'sender@example.com'; // Replace these sample addresses with the addresses of your recipients. If // your account is still in the sandbox, these addresses must be verified. $recipient_emails = ['recipient1@example.com','recipient2@example.com']; // Specify a configuration set. If you do not want to use a configuration // set, comment the following variable, and the // 'ConfigurationSetName' => $configuration_set argument below. $configuration_set = 'ConfigSet'; $subject = 'Amazon SES test (AWS SDK for PHP)'; $plaintext_body = 'This email was sent with Amazon SES using the AWS SDK for PHP.' ; $html_body = '<h1>AWS Amazon Simple Email Service Test Email</h1>'. '<p>This email was sent with <a href="https://aws.amazon.com/ses/">'. 'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-php/">'. 'AWS SDK for PHP</a>.</p>'; $char_set = 'UTF-8'; try { $result = $SesClient->sendEmail([ 'Destination' => [ 'ToAddresses' => $recipient_emails, ], 'ReplyToAddresses' => [$sender_email], 'Source' => $sender_email, 'Message' => [ 'Body' => [ 'Html' => [ 'Charset' => $char_set, 'Data' => $html_body, ], 'Text' => [ 'Charset' => $char_set, 'Data' => $plaintext_body, ], ], 'Subject' => [ 'Charset' => $char_set, 'Data' => $subject, ], ], // If you aren't using a configuration set, comment or delete the // following line 'ConfigurationSetName' => $configuration_set, ]); $messageId = $result['MessageId']; echo("Email sent! Message ID: $messageId"."\n"); } catch (AwsException $e) { // output error message if fails echo $e->getMessage(); echo("The email was not sent. Error message: ".$e->getAwsErrorMessage()."\n"); echo "\n"; }
    2. amazon-ses-sample.php 中,将以下内容替换为您自己的值:

      • path_to_sdk_inclusion—替换为包含所需的路径 AWS SDK for PHP 在程序中。有关更多信息,请参阅 。AWS SDK for PHP 文档

      • sender@example.com—替换为您已向 Amazon SES 验证的电子邮件地址。有关更多信息,请参阅 已验证的身份。Amazon 中的电子邮件地址区SES分大小写。请确保您输入的地址与经验证的地址完全相同。

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

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

      • (可选)us-west-2— 如果您想在美国西部(俄勒冈)以外的地区使用 AmazonSES,请将其替换为您要使用的区域。有关提供亚马逊SES服务的地区列表,请参阅《亚马逊简单电子邮件服务》(AmazonSES) AWS 一般参考.

    3. 保存 amazon-ses-sample.php

    4. 要运行程序,请在 amazon-ses-sample.php 所在的同一目录中打开命令提示符,然后键入以下命令:

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

      注意

      如果您在运行该程序时遇到 “c URL error 60:SSL证书问题” 错误,请按照中的说明下载最新的 CA 包 AWS SDK for PHP 文档。然后,在 amazon-ses-sample.php 中,将以下行添加到 SesClient::factory 数组,将 path_of_certs 替换为您下载的 CA 捆绑的路径,然后重新运行程序。

      'http' => [ 'verify' => 'path_of_certs\ca-bundle.crt' ]
    6. 登录收件人地址的电子邮件客户端。您将看到已发送的电子邮件。

    Ruby

    本主题介绍如何使用 AWS SDK for Ruby通过 Amazon 发送电子邮件SES。

    在开始前,请执行以下任务:
    要通过 Amazon 发送电子邮件,SES请使用 AWS SDK for Ruby
    1. 在文本编辑器中,创建一个名为 amazon-ses-sample.rb 的文件。将以下代码粘贴到该文件中:

      require 'aws-sdk' # Replace sender@example.com with your "From" address. # This address must be verified with Amazon SES. sender = "sender@example.com" # 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" # Specify a configuration set. If you do not want to use a configuration # set, comment the following variable and the # configuration_set_name: configsetname argument below. configsetname = "ConfigSet" # Replace us-west-2 with the AWS Region you're using for Amazon SES. awsregion = "us-west-2" # The subject line for the email. subject = "Amazon SES test (AWS SDK for Ruby)" # The HTML body of the email. htmlbody = '<h1>Amazon SES test (AWS SDK for Ruby)</h1>'\ '<p>This email was sent with <a href="https://aws.amazon.com/ses/">'\ 'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-ruby/">'\ 'AWS SDK for Ruby</a>.' # The email body for recipients with non-HTML email clients. textbody = "This email was sent with Amazon SES using the AWS SDK for Ruby." # Specify the text encoding scheme. encoding = "UTF-8" # Create a new SES resource and specify a region ses = Aws::SES::Client.new(region: awsregion) # Try to send the email. begin # Provide the contents of the email. resp = ses.send_email({ destination: { to_addresses: [ recipient, ], }, message: { body: { html: { charset: encoding, data: htmlbody, }, text: { charset: encoding, data: textbody, }, }, subject: { charset: encoding, data: subject, }, }, source: sender, # Comment or remove the following line if you are not using # a configuration set configuration_set_name: configsetname, }) puts "Email sent!" # If something goes wrong, display an error message. rescue Aws::SES::Errors::ServiceError => error puts "Email not sent. Error message: #{error}" end
    2. amazon-ses-sample.rb 中,将以下内容替换为您自己的值:

      • sender@example.com—替换为您已向 Amazon SES 验证的电子邮件地址。有关更多信息,请参阅 已验证的身份。Amazon 中的电子邮件地址区SES分大小写。请确保您输入的地址与经验证的地址完全相同。

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

      • (可选)us-west-2— 如果您想在美国西部(俄勒冈)以外的地区使用 AmazonSES,请将其替换为您要使用的区域。有关提供亚马逊SES服务的地区列表,请参阅《亚马逊简单电子邮件服务》(AmazonSES) AWS 一般参考.

    3. 保存 amazon-ses-sample.rb

    4. 要运行程序,请在 amazon-ses-sample.rb 所在的目录中打开命令提示符,然后键入 ruby amazon-ses-sample.rb

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

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

    Python

    本主题介绍如何使用 AWS SDK for Python (Boto)通过 Amazon 发送电子邮件SES。

    在开始前,请执行以下任务:
    • 向@@ 亚马逊验证您的电子邮件地址 SES-在通过亚马逊发送电子邮件之前SES,您必须确认自己拥有发件人的电子邮件地址。如果您的账户仍在 Amazon SES 沙箱中,则还必须验证收件人的电子邮件地址。我们建议您使用 Amazon SES 控制台验证电子邮件地址。有关更多信息,请参阅 创建电子邮件地址身份

    • 拿你的 AWS 凭证 —你需要一个 AWS 访问密钥 ID 和 AWS SES使用访问亚马逊的秘密访问密钥SDK。您可以使用的 “安全证书” 页面找到您的证书 AWS Management Console。 有关证书的更多信息,请参阅Amazon SES 凭证的类型

    • 安装 Python —Python 已在 thon.org/downloads/ 上https://www.py线。本教程中的代码已使用 Python 2.7.6 和 Python 3.6.1 进行了测试。安装 Python 后,在环境变量中添加 Python 的路径,这样就能通过任何命令提示符运行 Python。

    • 安装 AWS SDK for Python (Boto)—有关下载和安装说明,请参阅 AWS SDK for Python (Boto) 文档。本教程中的示例代码已使用SDK适用于 Python 的 1.4.4 版本进行了测试。

    SES使用 Python 版通过亚马逊发送电子邮件 SDK
    1. 在文本编辑器中,创建一个名为 amazon-ses-sample.py 的文件。将以下代码粘贴到该文件中:

      import boto3 from botocore.exceptions import ClientError # Replace sender@example.com with your "From" address. # This address must be verified with Amazon SES. SENDER = "Sender Name <sender@example.com>" # 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" # Specify a configuration set. If you do not want to use a configuration # set, comment the following variable, and the # ConfigurationSetName=CONFIGURATION_SET argument below. CONFIGURATION_SET = "ConfigSet" # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES. AWS_REGION = "us-west-2" # The subject line for the email. SUBJECT = "Amazon SES Test (SDK for Python)" # The email body for recipients with non-HTML email clients. BODY_TEXT = ("Amazon SES Test (Python)\r\n" "This email was sent with Amazon SES using the " "AWS SDK for Python (Boto)." ) # The HTML body of the email. BODY_HTML = """<html> <head></head> <body> <h1>Amazon SES Test (SDK for Python)</h1> <p>This email was sent with <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the <a href='https://aws.amazon.com/sdk-for-python/'> AWS SDK for Python (Boto)</a>.</p> </body> </html> """ # The character encoding for the email. CHARSET = "UTF-8" # Create a new SES resource and specify a region. client = boto3.client('ses',region_name=AWS_REGION) # Try to send the email. try: #Provide the contents of the email. response = client.send_email( Destination={ 'ToAddresses': [ RECIPIENT, ], }, Message={ 'Body': { 'Html': { 'Charset': CHARSET, 'Data': BODY_HTML, }, 'Text': { 'Charset': CHARSET, 'Data': BODY_TEXT, }, }, 'Subject': { 'Charset': CHARSET, 'Data': SUBJECT, }, }, Source=SENDER, # If you are not using a configuration set, comment or delete the # following line ConfigurationSetName=CONFIGURATION_SET, ) # Display an error if something goes wrong. except ClientError as e: print(e.response['Error']['Message']) else: print("Email sent! Message ID:"), print(response['MessageId'])
    2. amazon-ses-sample.py 中,将以下内容替换为您自己的值:

      • sender@example.com—替换为您已向 Amazon SES 验证的电子邮件地址。有关更多信息,请参阅 已验证的身份。Amazon 中的电子邮件地址区SES分大小写。请确保您输入的地址与经验证的地址完全相同。

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

      • (可选)us-west-2— 如果您想在美国西部(俄勒冈)以外的地区使用 AmazonSES,请将其替换为您要使用的区域。有关提供亚马逊SES服务的地区列表,请参阅《亚马逊简单电子邮件服务》(AmazonSES) AWS 一般参考.

    3. 保存 amazon-ses-sample.py

    4. 要运行程序,请在 amazon-ses-sample.py 所在的目录中打开命令提示符,然后键入 python amazon-ses-sample.py

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

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