Amazon SNS message publishing - Amazon Simple Notification Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Amazon SNS message publishing

After you create an Amazon SNS topic and subscribe an endpoint to it, you can publish messages to the topic. When a message is published, Amazon SNS attempts to deliver the message to the subscribed endpoints.

To publish messages to Amazon SNS topics using the Amazon Web Services Management Console

  1. Sign in to the Amazon SNS console.

  2. In the left navigation pane, choose Topics.

  3. On the Topics page, select a topic, and then choose Publish message.

    The console opens the Publish message to topic page.

  4. In the Message details section, do the following:

    1. (Optional) Enter a message Subject.

    2. For a FIFO topic, enter a Message group ID. Messages in the same message group are delivered in the order that they are published.

    3. For a FIFO topic, enter a Message deduplication ID. This ID is optional if you enabled the Content-based message deduplication setting for the topic.

    4. (Optional) For mobile push notifications, enter a Time to Live (TTL) value in seconds. This is the amount of time that a push notification service—such as Apple Push Notification Service (APNs) or Firebase Cloud Messaging (FCM)—has to deliver the message to the endpoint.

  5. In the Message body section, do one of the following:

    1. Choose Identical payload for all delivery protocols, and then enter a message.

    2. Choose Custom payload for each delivery protocol, and then enter a JSON object to define the message to send for each delivery protocol.

      For more information, see Publishing with platform-specific payload.

  6. In the Message attributes section, add any attributes that you want Amazon SNS to match with the subscription attribute FilterPolicy to decide whether the subscribed endpoint is interested in the published message.

    1. For Type, choose an attribute type, such as String.Array.

      Note

      For attribute type String.Array, enclose the array in square brackets ([]). Within the array, enclose string values in double quotation marks. You don't need quotation marks for numbers or for the keywords true, false, and null.

    2. Enter an attribute Name, such as customer_interests.

    3. Enter an attribute Value, such as ["soccer", "rugby", "hockey"].

    If the attribute type is String, String.Array, or Number, Amazon SNS evaluates the message attribute against a subscription's filter policy (if present) before sending the message to the subscription given filter policy scope is not explicitly set to MessageBody.

    For more information, see Amazon SNS message attributes.

  7. Choose Publish message.

    The message is published to the topic, and the console opens the topic's Details page.

To publish a message to a topic using an Amazon SDK

To use an Amazon SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the Amazon SDKs and Tools Reference Guide.

The following code examples show how to publish messages 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.

using System; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example publishes a message to an Amazon Simple Notification /// Service (Amazon SNS) topic. The code uses the AWS SDK for .NET and /// .NET Core 5.0. /// </summary> public class PublishToSNSTopic { public static async Task Main() { string topicArn = "arn:aws:sns:us-east-2:000000000000:ExampleSNSTopic"; string messageText = "This is an example message to publish to the ExampleSNSTopic."; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); await PublishToTopicAsync(client, topicArn, messageText); } /// <summary> /// Publishes a message to an Amazon SNS topic. /// </summary> /// <param name="client">The initialized client object used to publish /// to the Amazon SNS topic.</param> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="messageText">The text of the message.</param> public static async Task PublishToTopicAsync( IAmazonSimpleNotificationService client, string topicArn, string messageText) { var request = new PublishRequest { TopicArn = topicArn, Message = messageText, }; var response = await client.PublishAsync(request); Console.WriteLine($"Successfully published message ID: {response.MessageId}"); } }
  • For API details, see Publish 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.

//! Send a message to an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param message: The message to publish. \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::publishToTopic(const Aws::String &message, const Aws::String &topicARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::PublishRequest request; request.SetMessage(message); request.SetTopicArn(topicARN); const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Message published successfully with id '" << outcome.GetResult().GetMessageId() << "'." << std::endl; } else { std::cerr << "Error while publishing message " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • For API details, see Publish 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.

package main import ( "context" "flag" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" ) // SNSPublishAPI defines the interface for the Publish function. // We use this interface to test the function using a mocked service. type SNSPublishAPI interface { Publish(ctx context.Context, params *sns.PublishInput, optFns ...func(*sns.Options)) (*sns.PublishOutput, error) } // PublishMessage publishes a message to an Amazon Simple Notification Service (Amazon SNS) topic // Inputs: // c is the context of the method call, which includes the Region // api is the interface that defines the method call // input defines the input arguments to the service call. // Output: // If success, a PublishOutput object containing the result of the service call and nil // Otherwise, nil and an error from the call to Publish func PublishMessage(c context.Context, api SNSPublishAPI, input *sns.PublishInput) (*sns.PublishOutput, error) { return api.Publish(c, input) } func main() { msg := flag.String("m", "", "The message to send to the subscribed users of the topic") topicARN := flag.String("t", "", "The ARN of the topic to which the user subscribes") flag.Parse() if *msg == "" || *topicARN == "" { fmt.Println("You must supply a message and topic ARN") fmt.Println("-m MESSAGE -t TOPIC-ARN") return } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := sns.NewFromConfig(cfg) input := &sns.PublishInput{ Message: msg, TopicArn: topicARN, } result, err := PublishMessage(context.TODO(), client, input) if err != nil { fmt.Println("Got an error publishing the message:") fmt.Println(err) return } fmt.Println("Message ID: " + *result.MessageId) }
  • For API details, see Publish 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 pubTopic(SnsClient snsClient, String message, String topicArn) { try { PublishRequest request = PublishRequest.builder() .message(message) .topicArn(topicArn) .build(); PublishResponse result = snsClient.publish(request); System.out.println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • For API details, see Publish 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 {PublishCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters var params = { Message: "MESSAGE_TEXT", // MESSAGE_TEXT TopicArn: "TOPIC_ARN", //TOPIC_ARN }; const run = async () => { try { const data = await snsClient.send(new PublishCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
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 pubTopic(topicArnVal: String, messageVal: String) { val request = PublishRequest { message = messageVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println("${result.messageId} message sent.") } }
  • For API details, see Publish 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; /** * Sends a message to an Amazon SNS topic. * * 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' ]); $message = 'This message is sent from a Amazon SNS code sample.'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->publish([ 'Message' => $message, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
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.

Publish a message with attributes so that a subscription can filter based on attributes.

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 publish_message(topic, message, attributes): """ Publishes a message, with attributes, to a topic. Subscriptions can be filtered based on message attributes so that a subscription receives messages only when specified attributes are present. :param topic: The topic to publish to. :param message: The message to publish. :param attributes: The key-value attributes to attach to the message. Values must be either `str` or `bytes`. :return: The ID of the message. """ try: att_dict = {} for key, value in attributes.items(): if isinstance(value, str): att_dict[key] = {'DataType': 'String', 'StringValue': value} elif isinstance(value, bytes): att_dict[key] = {'DataType': 'Binary', 'BinaryValue': value} response = topic.publish(Message=message, MessageAttributes=att_dict) message_id = response['MessageId'] logger.info( "Published message with attributes %s to topic %s.", attributes, topic.arn) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id

Publish a message that takes different forms based on the protocol of the subscriber.

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 publish_multi_message( topic, subject, default_message, sms_message, email_message): """ Publishes a multi-format message to a topic. A multi-format message takes different forms based on the protocol of the subscriber. For example, an SMS subscriber might receive a short, text-only version of the message while an email subscriber could receive an HTML version of the message. :param topic: The topic to publish to. :param subject: The subject of the message. :param default_message: The default version of the message. This version is sent to subscribers that have protocols that are not otherwise specified in the structured message. :param sms_message: The version of the message sent to SMS subscribers. :param email_message: The version of the message sent to email subscribers. :return: The ID of the message. """ try: message = { 'default': default_message, 'sms': sms_message, 'email': email_message } response = topic.publish( Message=json.dumps(message), Subject=subject, MessageStructure='json') message_id = response['MessageId'] logger.info("Published multi-format message to topic %s.", topic.arn) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id
  • For API details, see Publish 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 message_sent?(sns_client, topic_arn, message) sns_client.publish(topic_arn: topic_arn, message: message) rescue StandardError => e puts "Error while sending the message: #{e.message}" end def run_me topic_arn = "SNS_TOPIC_ARN" region = "REGION" message = "MESSAGE" # The text of the message to send. sns_client = Aws::SNS::Client.new(region: region) puts "Message sending." if message_sent?(sns_client, topic_arn, message) puts "The message was sent." else puts "The message was not sent. Stopping program." exit 1 end end run_me if $PROGRAM_NAME == __FILE__
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 Publish 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->publish( " oo_result is returned for testing purposes. " iv_topicarn = iv_topic_arn iv_message = iv_message ). MESSAGE 'Message published to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY.
  • For API details, see Publish in Amazon SDK for SAP ABAP API reference.