Subscribe an email address to an Amazon SNS topic using an Amazon SDK
The following code examples show how to subscribe an email address to an Amazon SNS topic.
- .NET
-
- Amazon SDK for .NET
-
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. /// <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; }
-
For API details, see Subscribe in Amazon SDK for .NET API Reference.
-
- C++
-
- SDK for C++
-
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. /** * 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; }
-
For API details, see Subscribe in Amazon SDK for C++ API Reference.
-
- Go
-
- SDK for Go V2
-
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. -
For API details, see Subscribe
in Amazon SDK for Go API Reference.
-
- Java
-
- SDK for Java 2.x
-
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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); } }
-
For API details, see Subscribe in Amazon SDK for Java 2.x API Reference.
-
- JavaScript
-
- SDK for JavaScript (v3)
-
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. Create the client in a separate module and export it.
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 };
Import the SDK and client modules and call the 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();
-
For more information, see Amazon SDK for JavaScript Developer Guide.
-
For API details, see Subscribe in Amazon SDK for JavaScript API Reference.
-
- Kotlin
-
- SDK for Kotlin
-
Note This is prerelease documentation for a feature in preview release. It is subject to change.
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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() } }
-
For API details, see Subscribe
in Amazon SDK for Kotlin API reference.
-
- PHP
-
- SDK for PHP
-
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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()); }
-
For API details, see Subscribe in Amazon SDK for PHP API Reference.
-
- Python
-
- SDK for Python (Boto3)
-
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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
-
For API details, see Subscribe in Amazon SDK for Python (Boto3) API Reference.
-
- Ruby
-
- SDK for Ruby
-
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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__
-
For more information, see Amazon SDK for Ruby Developer Guide.
-
For API details, see Subscribe in Amazon SDK for Ruby API Reference.
-
- Rust
-
- SDK for Rust
-
Note This documentation is for an SDK in preview release. The SDK is subject to change and should not be used in production.
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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(()) }
-
For API details, see Subscribe
in Amazon SDK for Rust API reference.
-
- SAP ABAP
-
- SDK for SAP ABAP
-
Note This documentation is for an SDK in developer preview release. The SDK is subject to change and is not recommended for use in production.
Note There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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.
-
For API details, see Subscribe in Amazon SDK for SAP ABAP API reference.
-
For a complete list of Amazon SDK developer guides and code examples, see Using Amazon SNS with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.