电子邮件通知 - Amazon Simple Notification Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

电子邮件通知

本页将介绍如何使用 Amazon Web Services Management Console、Amazon SDK for Java 或 Amazon SDK for .NET 将电子邮件地址订阅到 Amazon SNS 主题。

注意
  • 您无法自定义电子邮件消息的正文。电子邮件传输功能旨在提供内部系统提示,而不是营销消息。

  • 电子邮件传输吞吐量根据 Amazon SNS 配额进行限制。

重要

要防止邮件列表接收人取消订阅来自 Amazon SNS 主题电子邮件的所有接收人,请参阅设置需要身份验证才能从 Amazon 支持取消订阅的电子邮件订阅

要使用 Amazon Web Services Management Console 将电子邮件地址订阅到 Amazon SNS 主题

  1. 登录 Amazon SNS 控制台

  2. 在左侧导航窗格中,选择订阅

  3. Subscriptions(订阅)页面上,选择 Create subscription(创建订阅)。

  4. Create subscription(创建订阅)页上的 Details(详细信息)部分中,执行以下操作:

    1. 对于 Topic ARN(主题 ARN),选择主题的 Amazon Resource Name (ARN)。

    2. 对于协议,选择电子邮件

    3. 对于 Endpoint(终端节点),输入电子邮件地址。

    4. (可选)要配置筛选策略,请展开 Subscription filter policy(订阅筛选策略)部分。有关更多信息,请参阅Amazon SNS 订阅筛选策略

    5. (可选)要为订阅配置死信队列,请展开 Redrive policy (dead-letter queue)(重新驱动策略(死信队列))部分。有关更多信息,请参阅Amazon SNS 死信队列 (DLQ)

    6. 选择 Create subscription(创建订阅)。

      控制台将创建订阅并打开订阅的 Details(详细信息)页面。

您必须先确认订阅,然后才能开始接收消息。

要确认订阅

  1. 检查您的电子邮件收件箱,然后从 Amazon SNS 中的电子邮件中选择 Confirm subscription(确认订阅)。

  2. Amazon SNS 会打开您的 Web 浏览器,并显示带有您的订阅 ID 的订阅确认信息。

要使用 Amazon 开发工具包将电子邮件地址订阅到 Amazon SNS 主题

要使用 Amazon 开发工具包,您必须使用您的凭证对其进行配置。有关更多信息,请参阅 Amazon 开发工具包和工具参考指南中的共享配置和凭证文件

以下代码示例显示如何将电子邮件地址订阅到 Amazon SNS 主题。

C++
SDK for C++

/** * Subscribe an email address endpoint to a topic - demonstrates how to initiate a subscription to an Amazon SNS topic with delivery * to an email address. * * SNS will send a subscription confirmation email to the email address provided which you need to confirm to * receive messages. * * <protocol_value> set to "email" provides delivery of message via SMTP (see https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html for available protocols). * <topic_arn_value> can be obtained from run_list_topics executable and includes the "arn:" prefix. */ int main(int argc, char ** argv) { if (argc != 4) { std::cout << "Usage: subscribe_email <protocol_value=email> <topic_arn_value>" " <email_address>" << std::endl; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { Aws::SNS::SNSClient sns; Aws::String protocol = argv[1]; Aws::String topic_arn = argv[2]; Aws::String endpoint = argv[3]; Aws::SNS::Model::SubscribeRequest s_req; s_req.SetTopicArn(topic_arn); s_req.SetProtocol(protocol); s_req.SetEndpoint(endpoint); auto s_out = sns.Subscribe(s_req); if (s_out.IsSuccess()) { std::cout << "Subscribed successfully " << std::endl; } else { std::cout << "Error while subscribing " << s_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options); return 0; }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 Subscribe

Go
SDK for Go V2
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 Subscribe

Java
SDK for Java 2.x

public static void subEmail(SnsClient snsClient, String topicArn, String email) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("email") .endpoint(email) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 Subscribe

JavaScript
SDK for JavaScript V3

在单独的模块中创建客户端并将其导出。

import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };

导入软件开发工具包和客户端模块,然后调用 API。

// Import required AWS SDK clients and commands for Node.js import {SubscribeCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { Protocol: "email" /* required */, TopicArn: "TOPIC_ARN", //TOPIC_ARN Endpoint: "EMAIL_ADDRESS", //EMAIL_ADDRESS }; const run = async () => { try { const data = await snsClient.send(new SubscribeCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

suspend fun subEmail(topicArnVal: String, email: String) : String { val request = SubscribeRequest { protocol = "email" endpoint = email returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) return result.subscriptionArn.toString() } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Kotlin API 参考中的 Unsubscribe

PHP
SDK for PHP

require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * Prepares to subscribe an endpoint by sending the endpoint a confirmation message. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $protocol = 'email'; $endpoint = 'sample@example.com'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->subscribe([ 'Protocol' => $protocol, 'Endpoint' => $endpoint, 'ReturnSubscriptionArn' => true, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅《Amazon SDK for PHP API 参考》中的 Subscribe

Python
SDK for Python (Boto3)

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def subscribe(topic, protocol, endpoint): """ Subscribes an endpoint to the topic. Some endpoint types, such as email, must be confirmed before their subscriptions are active. When a subscription is not confirmed, its Amazon Resource Number (ARN) is set to 'PendingConfirmation'. :param topic: The topic to subscribe to. :param protocol: The protocol of the endpoint, such as 'sms' or 'email'. :param endpoint: The endpoint that receives messages, such as a phone number (in E.164 format) for SMS messages, or an email address for email messages. :return: The newly added subscription. """ try: subscription = topic.subscribe( Protocol=protocol, Endpoint=endpoint, ReturnSubscriptionArn=True) logger.info("Subscribed %s %s to topic %s.", protocol, endpoint, topic.arn) except ClientError: logger.exception( "Couldn't subscribe %s %s to topic %s.", protocol, endpoint, topic.arn) raise else: return subscription
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Python (Boto3) API 参考中的 Subscribe

Ruby
SDK for Ruby

require 'aws-sdk-sns' # v2: require 'aws-sdk' def subscription_created?(sns_client, topic_arn, protocol, endpoint) sns_client.subscribe(topic_arn: topic_arn, protocol: protocol, endpoint: endpoint) rescue StandardError => e puts "Error while creating the subscription: #{e.message}" end # Full example call: def run_me protocol = 'email' endpoint = 'EMAIL_ADDRESS' topic_arn = 'TOPIC_ARN' region = 'REGION' sns_client = Aws::SNS::Client.new(region: region) puts "Creating the subscription." if subscription_created?(sns_client, topic_arn, protocol, endpoint) puts 'The subscriptions was created.' else puts 'The subscription was not created. Stopping program.' exit 1 end end run_me if $PROGRAM_NAME == __FILE__
Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

async fn subscribe_and_publish( client: &Client, topic_arn: &str, email_address: &str, ) -> Result<(), Error> { println!("Receiving on topic with ARN: `{}`", topic_arn); let rsp = client .subscribe() .topic_arn(topic_arn) .protocol("email") .endpoint(email_address) .send() .await?; println!("Added a subscription: {:?}", rsp); let rsp = client .publish() .topic_arn(topic_arn) .message("hello sns!") .send() .await?; println!("Published message: {:?}", rsp); Ok(()) }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Rust API 参考中的 Subscribe