Notificações por e-mail - Amazon Simple Notification Service

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Notificações por e-mail

Esta página descreve como inscrever um endereço de e-mail em um tópico do Amazon SNS usando o AWS Management Console, AWS SDK for Java, ou. AWS SDK for .NET

Observações
  • Não é possível personalizar o corpo da mensagem de e-mail. O recurso de entrega de e-mail destina-se a fornecer alertas internos do sistema, não mensagens de marketing.

  • A assinatura direta de endpoints de e-mail só é compatível com tópicos-padrão.

  • A taxa de transferência de entrega de e-mail é limitada de acordo com as Cotas do Amazon SNS.

Importante

Para evitar que os destinatários da lista de e-mails cancelem a assinatura de todos os destinatários dos e-mails de tópicos do Amazon SNS, consulte Configurar uma assinatura de e-mail que requer autenticação para cancelar a assinatura no AWS Support.

Para inscrever um endereço de e-mail em um tópico do Amazon SNS usando o AWS Management Console

  1. Faça login no console do Amazon SNS.

  2. No painel de navegação à esquerda, escolha Assinaturas.

  3. Na página Subscriptions (Assinaturas), escolha Create subscription (Criar assinatura).

  4. Na página Create subscription (Criar inscrição), na seção Details (detalhes), faça o seguinte:

    1. Em Topic ARN (ARN do tópico), escolha o nome do recurso da Amazon (ARN) de um tópico.

    2. Em Protocolo, escolha Email.

    3. Para Endpoint, insira o endereço de e-mail.

    4. (Opcional) Para configurar uma política de filtros, expanda a seção Subscription filter policy (Política de filtro de assinatura). Para ter mais informações, consulte Políticas de filtro de assinatura do Amazon SNS.

    5. (Opcional) Para habilitar a filtragem baseada em carga útil, configure Filter Policy Scope como MessageBody. Para ter mais informações, consulte Escopo de política de filtro de assinaturas do Amazon SNS.

    6. (Opcional) Para configurar uma fila de mensagens mortas para a assinatura, expanda a seção Redrive policy (dead-letter queue) (Política de redirecionamento (fila de mensagens mortas)). Para ter mais informações, consulte Filas de mensagens mortas (DLQs) do Amazon SNS.

    7. Selecione Criar assinatura.

      O console cria a assinatura e abre a página Details (Detalhes) da assinatura.

Você deve confirmar a assinatura para que o endereço de e-mail comece a receber mensagens.

Para confirmar uma assinatura
  1. Verifique sua caixa de entrada de e-mail e escolha Confirm subscription (Confirmar a assinatura) no e-mail do Amazon SNS.

  2. O Amazon SNS abre seu navegador da Web e exibe uma confirmação de assinatura com seu ID de assinatura.

Para inscrever um endereço de e-mail em um tópico do Amazon SNS usando um SDK AWS

Para usar um AWS SDK, você deve configurá-lo com suas credenciais. Para obter mais informações, consulte The shared config and credentials files (“Os arquivos compartilhados de configuração e de credenciais”) no Guia de referência de AWS SDKs e ferramentas.

Os exemplos de código a seguir mostram como usarSubscribe.

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva um endereço de e-mail em um tópico.

/// <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; }

Inscreva uma fila em um tópico com filtros opcionais.

/// <summary> /// Subscribe a queue to a topic with optional filters. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="useFifoTopic">The optional filtering policy for the subscription.</param> /// <param name="queueArn">The ARN of the queue.</param> /// <returns>The ARN of the new subscription.</returns> public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn) { var subscribeRequest = new SubscribeRequest() { TopicArn = topicArn, Protocol = "sqs", Endpoint = queueArn }; if (!string.IsNullOrEmpty(filterPolicy)) { subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } }; } var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest); return subscribeResponse.SubscriptionArn; }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for .NET .

C++
SDK for C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva um endereço de e-mail em um tópico.

//! 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(); }

Inscreva um aplicativo móvel em um tópico.

//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to a mobile app. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param endpointARN: The ARN for a mobile app or device endpoint. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeApp(const Aws::String &topicARN, const Aws::String &endpointARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("application"); request.SetEndpoint(endpointARN); 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(); }

Inscreva uma função Lambda em um tópico.

//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an AWS Lambda function. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param lambdaFunctionARN: The ARN for an AWS Lambda function. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeLambda(const Aws::String &topicARN, const Aws::String &lambdaFunctionARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("lambda"); request.SetEndpoint(lambdaFunctionARN); 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(); }

Inscreva uma fila SQS em um tópico.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; }

Inscreva-se com um filtro para um tópico.

static const Aws::String TONE_ATTRIBUTE("tone"); static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious", "sincere"}; Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); if (isFifoTopic) { if (first) { std::cout << "Subscriptions to a FIFO topic can have filters." << std::endl; std::cout << "If you add a filter to this subscription, then only the filtered messages " << "will be received in the queue." << std::endl; std::cout << "For information about message filtering, " << "see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html" << std::endl; std::cout << "For this example, you can filter messages by a \"" << TONE_ATTRIBUTE << "\" attribute." << std::endl; } std::ostringstream ostringstream; ostringstream << "Filter messages for \"" << queueName << "\"'s subscription to the topic \"" << topicName << "\"? (y/n)"; // Add filter if user answers yes. if (askYesNoQuestion(ostringstream.str())) { Aws::String jsonPolicy = getFilterPolicyFromUser(); if (!jsonPolicy.empty()) { filteringMessages = true; std::cout << "This is the filter policy for this subscription." << std::endl; std::cout << jsonPolicy << std::endl; request.AddAttributes("FilterPolicy", jsonPolicy); } else { std::cout << "Because you did not select any attributes, no filter " << "will be added to this subscription." << std::endl; } } } // if (isFifoTopic) Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } //! Routine that lets the user select attributes for a subscription filter policy. /*! \sa getFilterPolicyFromUser() \return Aws::String: The filter policy as JSON. */ Aws::String AwsDoc::TopicsAndQueues::getFilterPolicyFromUser() { std::cout << "You can filter messages by one or more of the following \"" << TONE_ATTRIBUTE << "\" attributes." << std::endl; std::vector<Aws::String> filterSelections; int selection; do { for (size_t j = 0; j < TONES.size(); ++j) { std::cout << " " << (j + 1) << ". " << TONES[j] << std::endl; } selection = askQuestionForIntRange( "Enter a number (or enter zero to stop adding more). ", 0, static_cast<int>(TONES.size())); if (selection != 0) { const Aws::String &selectedTone(TONES[selection - 1]); // Add the tone to the selection if it is not already added. if (std::find(filterSelections.begin(), filterSelections.end(), selectedTone) == filterSelections.end()) { filterSelections.push_back(selectedTone); } } } while (selection != 0); Aws::String result; if (!filterSelections.empty()) { std::ostringstream jsonPolicyStream; jsonPolicyStream << "{ \"" << TONE_ATTRIBUTE << "\": ["; for (size_t j = 0; j < filterSelections.size(); ++j) { jsonPolicyStream << "\"" << filterSelections[j] << "\""; if (j < filterSelections.size() - 1) { jsonPolicyStream << ","; } } jsonPolicyStream << "] }"; result = jsonPolicyStream.str(); } return result; }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for C++ .

CLI
AWS CLI

Para inscrever-se em um tópico

O comando subscribe a seguir inscreve um endereço de e-mail no tópico especificado.

aws sns subscribe \ --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \ --protocol email \ --notification-endpoint my-email@example.com

Saída:

{ "SubscriptionArn": "pending confirmation" }
  • Para obter detalhes da API, consulte Subscribe na Referência de comandos da AWS CLI .

Go
SDK for Go V2
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva uma fila em um tópico com filtros opcionais.

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // SubscribeQueue subscribes an Amazon Simple Queue Service (Amazon SQS) queue to an // Amazon SNS topic. When filterMap is not nil, it is used to specify a filter policy // so that messages are only sent to the queue when the message has the specified attributes. func (actor SnsActions) SubscribeQueue(topicArn string, queueArn string, filterMap map[string][]string) (string, error) { var subscriptionArn string var attributes map[string]string if filterMap != nil { filterBytes, err := json.Marshal(filterMap) if err != nil { log.Printf("Couldn't create filter policy, here's why: %v\n", err) return "", err } attributes = map[string]string{"FilterPolicy": string(filterBytes)} } output, err := actor.SnsClient.Subscribe(context.TODO(), &sns.SubscribeInput{ Protocol: aws.String("sqs"), TopicArn: aws.String(topicArn), Attributes: attributes, Endpoint: aws.String(queueArn), ReturnSubscriptionArn: true, }) if err != nil { log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n", queueArn, topicArn, err) } else { subscriptionArn = *output.SubscriptionArn } return subscriptionArn, err }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for Go .

Java
SDK para Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva um endereço de e-mail em um tópico.

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); } } }

Inscreva um endpoint HTTP em um tópico.

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 SubscribeHTTPS { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <url> Where: topicArn - The ARN of the topic to subscribe. url - The HTTPS endpoint that you want to receive notifications. """; if (args.length < 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String url = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subHTTPS(snsClient, topicArn, url); snsClient.close(); } public static void subHTTPS(SnsClient snsClient, String topicArn, String url) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("https") .endpoint(url) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN is " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

Inscreva uma função Lambda em um tópico.

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 SubscribeLambda { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <lambdaArn> Where: topicArn - The ARN of the topic to subscribe. lambdaArn - The ARN of an AWS Lambda function. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String lambdaArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnValue = subLambda(snsClient, topicArn, lambdaArn); System.out.println("Subscription ARN: " + arnValue); snsClient.close(); } public static String subLambda(SnsClient snsClient, String topicArn, String lambdaArn) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("lambda") .endpoint(lambdaArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); return result.subscriptionArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for Java 2.x .

JavaScript
SDK para JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Crie o cliente em um módulo separado e exporte-o.

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({});

Importe o SDK e os módulos do cliente e chame a 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' // } };

Inscreva um aplicativo móvel em um tópico.

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of an application. This endpoint is created * when an application registers for notifications. */ export const subscribeApp = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "application", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };

Inscreva uma função Lambda em um tópico.

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function. */ export const subscribeLambda = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "lambda", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };

Inscreva uma fila SQS em um tópico.

import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueue = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, Protocol: "sqs", Endpoint: queueArn, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue-test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };

Inscreva-se com um filtro para um tópico.

import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueueFiltered = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, Protocol: "sqs", Endpoint: queueArn, Attributes: { // This subscription will only receive messages with the 'event' attribute set to 'order_placed'. FilterPolicyScope: "MessageAttributes", FilterPolicy: JSON.stringify({ event: ["order_placed"], }), }, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue-test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };
Kotlin
SDK for Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva um endereço de e-mail em um tópico.

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() } }

Inscreva uma função Lambda em um tópico.

suspend fun subLambda(topicArnVal: String?, lambdaArn: String?) { val request = SubscribeRequest { protocol = "lambda" endpoint = lambdaArn returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) println(" The subscription Arn is ${result.subscriptionArn}") } }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for Kotlin.

PHP
SDK para PHP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva um endereço de e-mail em um tópico.

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()); }

Inscreva um endpoint HTTP em um tópico.

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 = 'https'; $endpoint = 'https://'; $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()); }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for PHP .

Python
SDK para Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva um endereço de e-mail em um tópico.

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
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for Python (Boto3).

Ruby
SDK for Ruby
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva um endereço de e-mail em um tópico.

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
Rust
SDK for Rust
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva um endereço de e-mail em um tópico.

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(()) }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for Rust.

SAP ABAP
SDK para SAP ABAP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Inscreva um endereço de e-mail em um tópico.

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.
  • Para obter detalhes da API, consulte Inscrever-se na Referência da API do AWS SDK para SAP ABAP.