Email notifications
This page describes how to subscribe an email
address to an Amazon SNS topic using the AWS Management Console, AWS SDK for Java, or AWS SDK for .NET.
-
You can't customize the body of the email message. The email delivery feature
is intended to provide internal system alerts, not marketing messages.
-
Email delivery throughput is throttled according to Amazon SNS quotas.
To subscribe an email
address to an Amazon SNS topic using the AWS Management Console
Sign in to the Amazon SNS console.
-
In the left navigation pane, choose Subscriptions.
-
On the Subscriptions page, choose Create
subscription.
-
On the Create subscription page, in the
Details section, do the following:
-
For Topic ARN, choose the Amazon Resource Name
(ARN) of a topic.
-
For Protocol, choose
Email.
-
For Endpoint, enter the email address.
-
(Optional) To configure a filter policy, expand the
Subscription filter policy section. For more
information, see Amazon SNS subscription filter
policies.
-
(Optional) To enable payload-based filtering, configure Filter
Policy Scope
to MessageBody
. For more
information, see Amazon SNS subscription filter policy
scope.
-
(Optional) To configure a dead-letter queue for the subscription,
expand the Redrive policy (dead-letter queue)
section. For more information, see Amazon SNS dead-letter queues (DLQs).
-
Choose Create subscription.
The console creates the subscription and opens the subscription's
Details page.
You must confirm the subscription before the email address can start to receive
messages.
To confirm a subscription
-
Check your email inbox and choose Confirm subscription in
the email from Amazon SNS.
-
Amazon SNS opens your web browser and displays a subscription confirmation with
your subscription ID.
To subscribe an email address to an
Amazon SNS topic using an AWS SDK
To use an AWS SDK, you must configure it with your credentials. For more
information, see The shared config and credentials
files in the AWS SDKs and Tools Reference Guide.
The following code examples show how to subscribe an email address to an Amazon SNS topic.
- .NET
-
- AWS SDK for .NET
-
/// <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;
}
- C++
-
- SDK for C++
-
//! 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();
}
- Go
-
- SDK for Go V2
-
package main
import (
"context"
"flag"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sns"
)
// SNSSubscribeAPI defines the interface for the Subscribe function.
// We use this interface to test the function using a mocked service.
type SNSSubscribeAPI interface {
Subscribe(ctx context.Context,
params *sns.SubscribeInput,
optFns ...func(*sns.Options)) (*sns.SubscribeOutput, error)
}
// SubscribeTopic subscribes a user to an Amazon Simple Notification Service (Amazon SNS) topic by their email address
// 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 SubscribeOutput object containing the result of the service call and nil
// Otherwise, nil and an error from the call to Subscribe
func SubscribeTopic(c context.Context, api SNSSubscribeAPI, input *sns.SubscribeInput) (*sns.SubscribeOutput, error) {
return api.Subscribe(c, input)
}
func main() {
email := flag.String("e", "", "The email address of the user subscribing to the topic")
topicARN := flag.String("t", "", "The ARN of the topic to which the user subscribes")
flag.Parse()
if *email == "" || *topicARN == "" {
fmt.Println("You must supply an email address and topic ARN")
fmt.Println("-e EMAIL -t TOPIC-ARN")
return
}
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
panic("configuration error, " + err.Error())
}
client := sns.NewFromConfig(cfg)
input := &sns.SubscribeInput{
Endpoint: email,
Protocol: aws.String("email"),
ReturnSubscriptionArn: true, // Return the ARN, even if user has yet to confirm
TopicArn: topicARN,
}
result, err := SubscribeTopic(context.TODO(), client, input)
if err != nil {
fmt.Println("Got an error subscribing to the topic:")
fmt.Println(err)
return
}
fmt.Println(*result.SubscriptionArn)
}
- Java
-
- SDK for Java 2.x
-
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);
}
}
- JavaScript
-
- SDK for JavaScript (v3)
-
Create the client in a separate module and export it.
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({});
Import the SDK and client modules and call the 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'
// }
};
- Kotlin
-
- SDK for Kotlin
-
This is prerelease documentation for a feature in preview release. It is subject to change.
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()
}
}
- PHP
-
- SDK for PHP
-
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());
}
- Python
-
- SDK for Python (Boto3)
-
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
- Ruby
-
- SDK for Ruby
-
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__
- Rust
-
- SDK for Rust
-
This documentation is for an SDK in preview release. The SDK is subject to change and should not be used in production.
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(())
}
- SAP ABAP
-
- SDK for SAP ABAP
-
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.