이메일 알림 - Amazon Simple Notification Service

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

이메일 알림

이 페이지에서는 AWS Management Console AWS SDK for Java, 또는 를 사용하여 Amazon SNS 주제에 이메일 주소를 구독하는 방법을 설명합니다 AWS SDK for .NET.

참고
  • 이메일 메시지의 본문을 사용자 지정할 수 없습니다. 이메일 전송 기능은 마케팅 메시지가 아닌 내부 시스템 알림을 제공하기 위한 것입니다.

  • 이메일 엔드포인트의 직접 구독은 표준 주제에만 지원됩니다.

  • 이메일 전송 처리량은 Amazon SNS 할당량에 따라 제한됩니다.

중요

메일 그룹 수신자가 모든 수신자에 대해 Amazon SNS 주제 이메일의 구독을 취소하는 것을 방지하려면 AWS Support에서 인증을 해야만 취소할 수 있는 이메일 구독 설정을 참조하세요.

를 사용하여 Amazon SNS 주제에 이메일 주소를 구독하려면 AWS Management Console

  1. Amazon SNS 콘솔에 로그인합니다.

  2. 왼쪽의 탐색 창에서 구독을 선택합니다.

  3. 구독 페이지에서 구독 생성을 선택합니다.

  4. 구독 생성 페이지의 세부 정보 섹션에서 다음을 수행합니다.

    1. 주제 ARN에서 주제의 Amazon 리소스 이름(ARN)을 선택합니다.

    2. 프로토콜에서 이메일을 선택합니다.

    3. 엔드포인트에 이메일 주소를 입력합니다.

    4. (선택 사항) 필터 정책을 구성하려면 구독 필터 정책 섹션을 확장합니다. 자세한 정보는 Amazon SNS 구독 필터 정책을 참조하세요.

    5. (선택 사항) 페이로드 기반 필터링을 활성화하려면 Filter Policy ScopeMessageBody로 구성하십시오. 자세한 정보는 Amazon SNS 구독 필터 정책 범위을 참조하세요.

    6. (선택 사항) 구독에 대한 배달 못한 편지 대기열을 구성하려면 리드라이브 정책(배달 못한 편지 대기열) 섹션을 확장합니다. 자세한 정보는 Amazon SNS 배달 못한 편지 대기열(DLQ)을 참조하세요.

    7. 구독 생성을 선택합니다.

      콘솔에서 구독을 만들고 구독의 세부 정보 페이지를 엽니다.

수신자가 구독을 확인해야만 이 이메일 주소가 메시지를 수신할 수 있습니다.

구독을 확인하려면
  1. 이메일 받은 편지함을 확인하고 Amazon SNS의 이메일에서 구독 확인을 선택합니다.

  2. Amazon SNS가 웹 브라우저를 열고 구독 ID와 함께 구독 확인을 표시합니다.

AWS SDK를 사용하여 Amazon SNS 주제에 이메일 주소를 구독하려면

AWS SDK를 사용하려면 사용자 인증 정보로 구성해야 합니다. 자세한 정보는 AWS SDK 및 도구 참조 가이드의 공유 구성 및 자격 증명 파일을 참조하세요.

다음 코드 예제는 Subscribe의 사용 방법을 보여줍니다.

.NET
AWS SDK for .NET
참고

자세한 내용은 에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

주제에 대한 이메일 주소를 구독하세요.

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

선택적 필터를 사용하여 주제 대기열을 구독하세요.

/// <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; }
  • API 세부 정보는 AWS SDK for .NET API 참조Subscribe를 참조하십시오.

C++
SDK for C++
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

주제에 대한 이메일 주소를 구독하세요.

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

모바일 애플리케이션을 구독하여 주제를 구독하십시오.

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

Lambda 함수를 구독하여 주제를 등록하십시오.

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

SQS 대기열에서 주제를 구독하십시오.

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

필터를 사용하여 주제를 구독하십시오.

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; }
  • API 세부 정보는 AWS SDK for C++ API 참조Subscribe를 참조하십시오.

CLI
AWS 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 세부 정보는 AWS CLI 명령 참조Subscribe를 참조하세요.

Go
SDK for Go V2
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

선택적 필터를 사용하여 주제 대기열을 구독하세요.

// 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 }
  • API 세부 정보는 AWS SDK for Go API 참조Subscribe를 참조하십시오.

Java
SDK for Java 2.x
참고

더 많은 것이 있어요 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

주제에 대한 이메일 주소를 구독하세요.

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

주제에 대한 HTTP 엔드포인트를 구독하십시오.

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

Lambda 함수를 구독하여 주제를 등록하십시오.

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 ""; } }
  • API 세부 정보는 AWS SDK for Java 2.x API 참조Subscribe를 참조하십시오.

JavaScript
(v3) 용 JavaScript SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

별도의 모듈에서 클라이언트를 생성하고 내보냅니다.

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

모바일 애플리케이션에서 주제를 구독하세요.

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

Lambda 함수를 구독하여 주제를 등록하십시오.

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

SQS 대기열에서 주제를 구독하십시오.

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

필터를 사용하여 주제를 구독하십시오.

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
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

주제에 대한 이메일 주소를 구독하세요.

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

Lambda 함수를 구독하여 주제를 등록하십시오.

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}") } }
  • API 세부 정보는 AWS SDK for Kotlin API 참조Subscribe를 참조하십시오.

PHP
SDK for PHP
참고

더 많은 정보가 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

주제에 대한 이메일 주소를 구독하세요.

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

주제에 대한 HTTP 엔드포인트를 구독하십시오.

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()); }
  • API 세부 정보는 AWS SDK for PHP API 참조Subscribe를 참조하십시오.

Python
SDK for Python(Boto3)
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

주제에 대한 이메일 주소를 구독하세요.

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 세부 정보는 AWS SDK for Python (Boto3) API 참조Subscribe를 참조하십시오.

Ruby
SDK for Ruby
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

주제에 대한 이메일 주소를 구독하세요.

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
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

주제에 대한 이메일 주소를 구독하세요.

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 세부 정보는 AWS SDK for Rust API 참조Subscribe을 참조하십시오.

SAP ABAP
SAP ABAP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

주제에 대한 이메일 주소를 구독하세요.

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.