Skip to main content

How to Send SMS with AWS SNS using Lambda & Python

In this article, we will discuss "How to Send SMS with AWS SNS using Lambda & Python". Amazon Simple Notification Service (AWS SNS) is a fully managed messaging service. You can check here for the pricing-related query, also amazon provides us the free tier for the same. We can use this service to send OTP, notifications messages.

[caption id="attachment_2591" align="aligncenter" width="1325"] Source: https://aws.amazon.com/sns[/caption]









Prerequisites



  1. AWS Account

  2. AWS Management Console Access

  3. Basic knowledge of AWS, If you are new to AWS then read service pricing properly. Otherwise, AWS charges your card when the free tier limit is crossed.


Create AWS Access Key & Secret Key


Check my previous article "How to Create AWS IAM User with Programmatic Access".

After creating the IAM user, you got your Access Key and Secret Key. Those are used with SDK to send SMS.

Create Lambda Function


Go to Lambda Console on your AWS management console. Then click on create function.



There are four options available, here we have to choose "Author from Scratch" and fill in the basic information.





As per the screenshot:

  • For the execution role, we will choose to "Create a new role with basic Lambda permissions".

  • In the advanced settings, there are other configurations but no need to apply any change. We will discuss more on the same in our future articles.


Click the "Create Function" button. Our function "pySMS" is created, your Lambda Dashboard will look like this.



Open "lambda_function.py" and update the following code.
import boto3
import sys
import os

def lambda_handler(event, context):
try:
client = boto3.client(
"sns",
aws_access_key_id=os.environ.get('AWS_USER_ACCESS_KEY'),
aws_secret_access_key=os.environ.get('AWS_USER_SECRET_KEY'),
region_name="us-east-1"
)

client.set_sms_attributes(
attributes=
'DefaultSMSType': 'Transactional',
'DeliveryStatusSuccessSamplingRate': '100',
'DefaultSenderID': 'CodeBriefly'

)

# Send your sms message.
response = client.publish(
PhoneNumber="+1xxxxxxxxxx",
Message="Hello, this is the test message AWS SNS!"
)
# print(response)
except:
print('Error', sys.exc_info()[0])

You have to use the region as per your needs, check here for more details. Let's attach the required policies to our lambda function. You can find this under the Configuration -> Permissions tab.



Adding policies to the lambda function. I’ve attached AmazonSNSFullAccess which means Lambda has full access to SNS.



Now, time to deploy our code.



Let's test our code, we have to "configure test event". Choose "Create new test event" and enter the event name, then click on save.

All are good, just need to click on the test button. I'm using my skype US number for testing and got my testing message.


Conclusion


I hope you enjoyed this article, today we've explored "How to send SMS with AWS SNS using Lambda & Python". We will discuss more on the SNS, Lambda, Boto3, and other AWS services in our future articles. Please feel free to add a comment if any queries.

Keep Learning, Stay Safe :)



You may like:


How to Create AWS IAM User with Programmatic Access


Handling Multiple File Upload in Laravel


Access Hosting Account using SSH Key with PuTTY

Comments

Popular posts from this blog

Basic Use of Model Factories in Laravel

In this article, we will discuss the basic use of Model Factories in Laravel. Laravel comes with the feature called model factories that are offered to made fake models quickly. It’s used in the database testing and database seeding. Let’s start the discussion on this feature by... Read out the full post at here

How to setup Amazon Kinesis Data Stream with Amazon Pinpoint (Part 3)?

In this article, we will discuss "How to setup Amazon Kinesis Data Stream with Amazon Pinpoint (Part 3)?". This article is the third part of our Amazon Pinpoint Series. For better understanding, I recommend to readout the previous article. How to Setup AWS Pinpoint (Part 1) How to Setup AWS Pinpoint SMS Two-Way Communication (Part 2)? Streaming Amazon Pinpoint events to Kinesis In Amazon Pinpoint, when we send a transactional SMS or email message then an event will occur as per the action performed. In a simple way, Amazon Pinpoint sends information about events to Amazon Kinesis. Which, we read and process as per our requirement. We are talking about the SMS so we read the stream data to fetch the delivery reports of our SMSs. There are two types of streams given by the Amazon Kinesis such as Data Firehose, and Data Streams. Amazon Pinpoint can also stream data to Kinesis Data Streams, which ingests and stores multiple data streams for processing by analytics applications. F...

How to Manage Elastic IP in AWS?

In this article, we will discuss "How to Manage Elastic IP in AWS?" . Here, you will learn the use of Elastic IP addresses and how to assign it to your EC2 Instance. If you are new with EC2 Instance then check out my previous article, "How to setup an EC2 Instance on AWS" . EC2 (Amazon Elastic Compute Cloud) provide us an ability to create, start, stop and terminate the instance at any time. This will creates a challenge with IP addresses, because restarting an instance or replacing a terminated instance with newly created instance, will result in a new IP address. Now the question is "How to reference a machine when the IP is constantly change?" . We can handle this situation with the use of Elastic IP address. We can associate a single Elastic IP address to different Ec2 Instances. You can immediately associate a new Ec2 Instance with the Elastic IP address if the EC2 instance is stopped or terminated. After the back-end EC2 instance changes, our exist...