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

Laravel Logging Guzzle Requests in File

In this article, we will discuss “Laravel Logging Guzzle Requests in File”. In the multiple scenarios, we have to use third-party API’s in our project and test those API using postman or any other tool. But also required to maintain a log for each request, such as what we send (request)? and what we receive (response)? Today, […] Read out the full post at here

How to Use SSH with AWS EC2 Instance?

In this article, we will discuss "How to Use SSH with AWS EC2 Instance?" . As I already explain the setup of EC2 Instance and the use of an Elastic IP in my previous article. Today, we will learn how to connect an EC2 instance using SSH. If still, you have not read my previous articles then I recommend checking them once for a better understanding. Prerequisites A running EC2 Instance . Elastic IP (Optional for this article) ".pem" file, which is downloaded when setup the EC2 Instance. If not having the ".pem" file, then you have to create new key/value pairs. Connect via Terminal or WSL(Window Subsystem for Linux) Open your terminal and go to the directory where you downloaded your ".pem" file. Use the following command to connect with the server. ssh -i "****.pem" username@<publicDNS> or <IP Address> The same terminal command can be used in the windows Linux terminal. I'm using ubuntu on my windows machine...

How to Setup and Install Next.js App?

In this article, we will discuss "How to Setup and Install Next.js App" from scratch. What is React.js and Next.js? "React.js" is a JavaScript library for building user interfaces (elements that users see and interacting on-screen). Basically, React provide us some helpful functions to build UI, and leaves it on us where to use those functions in the application. "Next.js" is a React framework. It is maintained by "Vercel" . Next.js features to solve common application requirements such as routing, data fetching, integrations - all while improving the developer and end-user experience. Why we use Next.js ? Next.js comes with the some additional features to solve come application requirements such as: We can build SSG (Static Site Generation), SSR (Server-Side Rendering) and SPA (Single Page Application) apps. Hot code Reloading: Reload the page when it detects any change saved. Routing: No need to configure any route. Files put in the pages fol...