本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
电子邮件通知
本页将介绍如何使用 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 主题
登录 Amazon SNS 控制台
。 -
在左侧导航窗格中,选择订阅。
-
在 Subscriptions(订阅)页面上,选择 Create subscription(创建订阅)。
-
在 Create subscription(创建订阅)页上的 Details(详细信息)部分中,执行以下操作:
-
对于 Topic ARN(主题 ARN),选择主题的 Amazon Resource Name (ARN)。
-
对于协议,选择电子邮件。
-
对于 Endpoint(终端节点),输入电子邮件地址。
-
(可选)要配置筛选策略,请展开 Subscription filter policy(订阅筛选策略)部分。有关更多信息,请参阅Amazon SNS 订阅筛选策略。
-
(可选)要启用基于有效负载的筛选,请将
Filter Policy Scope
配置为MessageBody
。有关更多信息,请参阅Amazon SNS 订阅筛选策略范围。 -
(可选)要为订阅配置死信队列,请展开 Redrive policy (dead-letter queue)(重新驱动策略(死信队列))部分。有关更多信息,请参阅Amazon SNS 死信队列 (DLQ)。
-
选择创建订阅。
控制台将创建订阅并打开订阅的 Details(详细信息)页面。
-
您必须先确认订阅,然后才能开始接收消息。
要确认订阅
-
检查您的电子邮件收件箱,然后从 Amazon SNS 中的电子邮件中选择 Confirm subscription(确认订阅)。
-
Amazon SNS 会打开您的 Web 浏览器,并显示带有您的订阅 ID 的订阅确认信息。
要使用 Amazon 开发工具包将电子邮件地址订阅到 Amazon SNS 主题
要使用 Amazon 开发工具包,您必须使用您的凭证对其进行配置。有关更多信息,请参阅 Amazon 开发工具包和工具参考指南中的共享配置和凭证文件。
以下代码示例显示如何将电子邮件地址订阅到 Amazon SNS 主题。
- .NET
-
- Amazon SDK for .NET
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 /// <summary> /// Creates a new subscription to a topic. /// </summary> /// <param name="client">The initialized Amazon SNS client object, used /// to create an Amazon SNS subscription.</param> /// <param name="topicArn">The ARN of the topic to subscribe to.</param> /// <returns>A SubscribeResponse object which includes the subscription /// ARN for the new subscription.</returns> public static async Task<SubscribeResponse> TopicSubscribeAsync( IAmazonSimpleNotificationService client, string topicArn) { SubscribeRequest request = new SubscribeRequest() { TopicArn = topicArn, ReturnSubscriptionArn = true, Protocol = "email", Endpoint = "recipient@example.com", }; var response = await client.SubscribeAsync(request); return response; }
-
有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 Subscribe。
-
- C++
-
- 适用于 C++ 的 SDK
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 //! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an email address. /*! \param topicARN: An SNS topic Amazon Resource Name (ARN). \param emailAddress: An email address. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeEmail(const Aws::String &topicARN, const Aws::String &emailAddress, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("email"); request.SetEndpoint(emailAddress); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
-
有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 Subscribe。
-
- CLI
-
- Amazon CLI
-
订阅主题
以下
subscribe
命令将电子邮件地址订阅到指定主题。aws sns subscribe \ --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \ --protocol email \ --notification-endpoint my-email@example.com
输出:
{ "SubscriptionArn": "pending confirmation" }
-
有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 Subscribe
。
-
- Java
-
- 适用于 Java 2.x 的 SDK
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class SubscribeEmail { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <email> Where: topicArn - The ARN of the topic to subscribe. email - The email address to use. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String email = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subEmail(snsClient, topicArn, email); snsClient.close(); } 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); } } }
-
有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 Subscribe。
-
- JavaScript
-
- 适用于 JavaScript (v3) 的软件开发工具包
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 在单独的模块中创建客户端并将其导出。
import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});
导入 SDK 和客户端模块,然后调用 API。
import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription. * @param {string} emailAddress - The email address that is subscribed to the topic. */ export const subscribeEmail = async ( topicArn = "TOPIC_ARN", emailAddress = "usern@me.com", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "email", TopicArn: topicArn, Endpoint: emailAddress, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } };
-
有关更多信息,请参阅 Amazon SDK for JavaScript 开发人员指南。
-
有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 Subscribe。
-
- Kotlin
-
- 适用于 Kotlin 的 SDK
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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() } }
-
有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 Subscribe
。
-
- PHP
-
- 适用于 PHP 的 SDK
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * 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()); }
-
有关 API 详细信息,请参阅 Amazon SDK for PHP API 参考中的 Subscribe。
-
- Python
-
- 适用于 Python (Boto3) 的 SDK
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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 @staticmethod 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
-
有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 Subscribe。
-
- Ruby
-
- 适用于 Ruby 的 SDK
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 require "aws-sdk-sns" require "logger" # Represents a service for creating subscriptions in Amazon Simple Notification Service (SNS) class SubscriptionService # Initializes the SubscriptionService with an SNS client # # @param sns_client [Aws::SNS::Client] The SNS client def initialize(sns_client) @sns_client = sns_client @logger = Logger.new($stdout) end # Attempts to create a subscription to a topic # # @param topic_arn [String] The ARN of the SNS topic # @param protocol [String] The subscription protocol (e.g., email) # @param endpoint [String] The endpoint that receives the notifications (email address) # @return [Boolean] true if subscription was successfully created, false otherwise def create_subscription(topic_arn, protocol, endpoint) @sns_client.subscribe(topic_arn: topic_arn, protocol: protocol, endpoint: endpoint) @logger.info("Subscription created successfully.") true rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error while creating the subscription: #{e.message}") false end end # Main execution if the script is run directly if $PROGRAM_NAME == __FILE__ protocol = "email" endpoint = "EMAIL_ADDRESS" # Should be replaced with a real email address topic_arn = "TOPIC_ARN" # Should be replaced with a real topic ARN sns_client = Aws::SNS::Client.new subscription_service = SubscriptionService.new(sns_client) @logger.info("Creating the subscription.") unless subscription_service.create_subscription(topic_arn, protocol, endpoint) @logger.error("Subscription creation failed. Stopping program.") exit 1 end end
-
有关更多信息,请参阅 Amazon SDK for Ruby 开发人员指南。
-
有关 API 详细信息,请参阅 Amazon SDK for Ruby API 参考中的 Subscribe。
-
- Rust
-
- 适用于 Rust 的 SDK
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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(()) }
-
有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 Subscribe
。
-
- SAP ABAP
-
- SDK for SAP ABAP
-
注意
还有更多相关信息 GitHub。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 TRY. oo_result = lo_sns->subscribe( "oo_result is returned for testing purposes." iv_topicarn = iv_topic_arn iv_protocol = 'email' iv_endpoint = iv_email_address iv_returnsubscriptionarn = abap_true ). MESSAGE 'Email address subscribed to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. CATCH /aws1/cx_snssubscriptionlmte00. MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'. ENDTRY.
-
有关 API 详细信息,请参阅《Amazon SDK for SAP ABAP API 参考》中的 Subscribe。
-