Sending Email Notifications with Amazon SNS Made Easy

Amazon AWS is arguably the world’s most popular cloud computing platform. It offers numerous services such as EC2, RDS, and VPC, but also a number of products for triggering messages. One of them is Amazon SNS. What is it about? How can it work with other services from the Amazon Cloud? Let’s see!

What is Amazon SNS?

SNS stands for Simple Notification Service and, unsurprisingly, that’s exactly what it does. Amazon SNS is about sending basic notifications that can take the form of mobile push notifications, SMS’s, and even emails. As well as mobile devices and email clients, these alerts can also be sent to various distributed services around the web.

Before you get your whole marketing team involved, be aware that SNS isn’t suitable for sending mass marketing campaigns and client-facing transactional email. That’s because of the way these notifications are triggered (more about this below), but also because there’s no space for any customization of emails, even with the most basic HTML (not to mention CSS). To send campaigns to your customers, have a look at Amazon SES (Simple Email Service), which we covered in detail in another article.

How does Amazon SNS work?

The way SNS works resembles mailing groups that you subscribe to in order to receive the content of interest to you. First of all, developers managing an account create a certain topic and publish it via the SNS dashboard. There can be a number of topics as it usually doesn’t make sense to send all the content to all the accounts within an organization. As a matter of fact, Amazon set the limit at 100,000 topics for a single AWS account.

A topic is an access point that users can subscribe to with a URL, a phone number or an email address to receive its respective notifications. When a new notification is published, it’s filtered to meet subscribers’ policies and, if successful, is delivered to the provided endpoint.

It’s important to note that, unlike SQS, SNS doesn’t guarantee delivery and won’t retry if sending is unsuccessful for whatever reason. If that happens, a message will be discarded.

What is Amazon SNS used for?

Simple Notification Service is frequently used to send system notifications to subscribers of a given topic. These can include alerts received when a server is down, when a new user registers, or when a recurring check is performed. Since different people are interested in different topics, usually dozens of them are created so as not to unnecessarily email or text an entire company.

Another popular use is with a common “fan-out” scenario that involves the use of Amazon SQS. 

As a reminder from our other article, Simple Queue Service is also used to distribute notifications to its users, or, to be precise, to their queues. The messages are not pushed to users, as was the case with SNS, but, instead, they need to “poll” a queue to obtain them. When they do, a message is no longer available for the rest of a network. Such communication guarantees a delivery because it’s asynchronous. Each message will patiently wait in a queue for its addressee to fetch it. This approach to delivering notifications raises an opportunity for an interesting integration with SNS, which bears the aforementioned “fan-out” name.

In this popular scenario, each new purchase from a store results in a new message sent to a topic. SNS then distributes it among its subscribers, sending each an identical message. These can be directed to an email address (a notification for a manager of a bought product), an HTTP/HTTPS endpoint (to update a client record in a CRM), and also to multiple SQS queues:

  • Queue 1 – sent to a warehouse so the staff there can pick up a product and pass it on to the next team
  • Queue 2 – sent to a purchasing department to keep them up-to-date about remaining stock
  • Queue 3 – sent to a shipping team to generate a shipping label and prepare the packaging

Another use of SNS-SQS collaboration is testing the internal workflows. In the example above, we could add a fourth SQS queue that would send all the order confirmations to the development environment of your application. There, production data could be used to eliminate the errors and push changes to the production environment afterwards. However, if you only need to test email workflows, an easier environment for testing would be with an external tool, such as Mailtrap.

For more detail on integrating SNS with SQS, refer to our article on Amazon SQS. See also a piece from Amazon AWS’s help center here.

How to use Amazon SNS?

Creating a topic

To get started, you’ll definitely need to create a topic to send notifications to. One way to do this is from within the AWS console. To do so, launch the SNS panel.

In there, pick “Select Topic” from the list or, if you don’t have any yet, create one directly from the home page. Enter its name and confirm that you want to create it.

You’ll be sent to a topic page to specify its parameters. You can, for example, choose who will be allowed to post to the topic or if an encryption method will be used. All settings are optional. When you’re finished, click on “Create topic”.

Adding subscribers to a topic

When a topic is created, you’ll be redirected to its details along with a dashboard displaying the list of subscribers. Add some subscribers here, specifying their protocols and endpoints. You can also add a separate filter policy that will be checked against a message policy to avoid messaging those not necessarily interested in a given message.

Note that each subscriber will need to confirm that they want to be added to the topic. Consult AWS’s help text from this screen for details.

Sending a message to a topic

Go back to the topic page and choose to publish a message.

In the “Message details” section, you can specify a subject for each notification, but it’s not mandatory. Then, in “Message body”, you need to pick from one of two options:

  • If you wish to send an identical notification to all subscribers, whether they signed up with a phone number, an SQS queue or an email, choose “Identical payload for all delivery protocols” and insert your message.
  • If, however, you want to send different content to each type of a subscriber, pick “Custom payload for each delivery protocol” and then insert a JSON object with instructions for each protocol. Here’s an example:
{
  "default": "Sample fallback message",
  "email": "Sample message for email endpoints",
  "sqs": "Sample message for Amazon SQS endpoints",
  "lambda": "Sample message for AWS Lambda endpoints",
  "http": "Sample message for HTTP endpoints",
  "https": "Sample message for HTTPS endpoints",
  "sms": "Sample message for SMS endpoints",
  "APNS": "{\"aps\":{\"alert\": \"Sample message for iOS endpoints\"} }",
  "APNS_SANDBOX": "{\"aps\":{\"alert\":\"Sample message for iOS development endpoints\"}}",
  "APNS_VOIP": "{\"aps\":{\"alert\":\"Sample message for Apple VoIP endpoints\"}}",
  "APNS_VOIP_SANDBOX": "{\"aps\":{\"alert\": \"Sample message for Apple VoIP development endpoints\"} }",
  "MACOS": "{\"aps\":{\"alert\":\"Sample message for MacOS endpoints\"}}",
  "MACOS_SANDBOX": "{\"aps\":{\"alert\": \"Sample message for MacOS development endpoints\"} }",
  "GCM": "{ \"data\": { \"message\": \"Sample message for Android endpoints\" } }",
  "ADM": "{ \"data\": { \"message\": \"Sample message for FireOS endpoints\" } }",
  "BAIDU": "{\"title\":\"Sample message title\",\"description\":\"Sample message for Baidu endpoints\"}",
  "MPNS": "<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification xmlns:wp=\"WPNotification\"><wp:Tile><wp:Count>ENTER COUNT</wp:Count><wp:Title>Sample message for Windows Phone 7+ endpoints</wp:Title></wp:Tile></wp:Notification>",
  "WNS": "<badge version=\"1\" value=\"42\"/>"
}

Before you publish a message to a topic, you can use the “Message attributes” window to filter out subscribers who might not be interested. Select the “Type” attribute, and enter the “Name” and “Value.” Using the subscription attribute, “Filter policy,” you can choose other attributes that you want to match. Subscribers who are matched by attribute are filtered out and will not receive the message. 

Read more about attributes in SNS docs here

When you’re finished, publish your message. You’ll then be redirected to a page with the details of the just sent message. 

Of course, You do not need to use the console to send each message. If you have many messages to send, you can use either AWS SDK for Java or for .NET.

Publishing a message with AWS SDK for Java

Specify your AWS credentials and type in your code. If you need help using Amazon SDK for Java 2.x, consult their guide. Here’s a sample of code that publishes a message and prints its ID.

Note that TopicArn refers to Amazon Resource Name, the topic that the endpoint is subscribed to.

// Publish a message to an Amazon SNS topic.
final String msg = "If you receive this message, publishing a message to an Amazon SNS topic works.";
final PublishRequest publishRequest = new PublishRequest(topicArn, msg);
final PublishResult publishResponse = snsClient.publish(publishRequest);

// Print the MessageId of the message.
System.out.println("MessageId: " + publishResponse.getMessageId());

Compile and run the code, and you’re done.

Publishing a message with AWS SDK for .NET

Begin by entering your credentials and the code for .NET. For details on using Amazon SDK with .NET, look here

Here’s another sample:

// Publish a message to an Amazon SNS topic.
String msg = "If you receive this message, publishing a message to an Amazon SNS topic works.";
PublishRequest publishRequest = new PublishRequest(topicArn, msg);
PublishResponse publishResponse = snsClient.Publish(publishRequest);

// Print the MessageId of the published message.
Console.WriteLine("MessageId: " + publishResponse.MessageId);

Simply compile it and your message will be sent to a topic, the site returning its MessageID.

Pricing of Amazon SNS

Amazon SNS if fairly inexpensive and comes with a generous free tier. There’s no subscription necessary. You simply pay for what you use at the type of endpoint you choose. Each month, you’ll get 1 million free mobile push notifications. After that, each delivered message is priced at $0.5 per million, but can also depend on the regions of your recipients. The free tier also includes 100 SMSes worldwide, one thousand emails (with or without JSON), and 100k HTTP requests. Deliveries to SQS Queues and Lambdas are free. 

For the most accurate information, see the AWS Calculator.

Things to consider when sending emails with Amazon SNS

As you can see in the examples above, there’s no way to customize the email notifications sent with SNS. While it’s fine to publish a plain-text message to a coworker’s endpoint saying “New order was received, ID 2378234234234, delivery method: DHL”, this won’t really appeal to many customers. To add HTML or richly formatted messages, you’ll need to integrate with an email service.

The simplest method is with Amazon Simple Email Service (SES). Have a look at this detailed guide on how to connect both services. 

If you prefer SendGrid, they also provide the integration with SNS as well as other AWS services.

Can’t decide which of the two would work best for you? Have a look at our Amazon SES vs SendGrid comparison.

Finally, to make things simpler, you can use Zapier to connect SendGrid and AWS SNS, and, for example, send an email from SendGrid the moment a new message is sent on a topic with AWS SNS.

Use Zapier also to integrate with other email service providers, such as Mailgun, Mailjet, SparkPost or just Gmail.

Alternatives to Amazon SNS

If, for some reason, you don’t want to use Amazon SNS after all, you’ll be happy to hear there are many alternatives. Exactly which one will work for you really depends on which features you need from the software.

If you care about SMS and voice messages the most, Twilio is definitely worth considering. With their numerous integrations and robust API, you’ll also have no problem sending notifications and pushing emails through the third-party solutions.

If push notifications are your main goal, Firebase stands out as the most popular solution for developers. Tools such as OneSignal and Pushwoosh are also close contenders, with each offering both mobile and web notifications for you to implement.

If this was all about emails after all, then a quick switch from SNS to SES may do the job. Still not a big fan of the AWS environment? Check out our list of the best platforms for sending transactional emails.

That’s all, folks! Until the next time.