AWS Lambda: Sending SMS using Python

cem akpolat
6 min readMay 26, 2022

--

In the previous article, AWS Lambda Sending Email using Python, is introduced and explained how it can be used. Sending SMS can also be quite interesting and useful for transmitting SMS to end users such as clients, system operators, etc. with the aim of informing the health status of the overall system. Text message sending is enabled by AWS SNS service and this service has a good deal of different utilization scenarios.

The implementation of AWS SMS lambda has similar steps as in AWS Email lambda:

  1. Create AWS Lambda
  2. Assign required AIM Roles
  3. Verify Phone Number
  4. Implement SMS lambda
  5. Test AWS Lambda & Check CloudWatch Logs
  1. Create AWS Lambda
  • Search for AWS Lambda in AWS Console, and click create a lambda button as below
  • Select the Author from scratch
  • Select the base image that you want to use, Python 3.9
  • Select the creation of AWS role automatically
  • Provide all required information such as name, and architecture
  • Do not change the default execution role, since a new one will be created for us
  • Once the lambda is created, you will see its name as below

2. Assign Required AIM Roles

  • Inside AWS Lambda under Configuration, click the execution role under the permissions section, this will navigate you to IAM roles, where you should add the required permission as JSON.
  • The arrived page does already show the existing policies attached to the role, our purpose is to extend it for sending SMS texts.
  • For the sake of simplicity, only two new permissions are added to the policy page as depicted below.
{
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:Publish",
"sns:SetSMSAttribute"
],
"Resource": "*"
}
]
}

These above permissions mean that you can send SMS using sns:Publishpermission, and set SMS attributes using sns:SetSMSAttribute.

The final IAM policy list should be seen as below. Two additional policies are added directly during the lambda creation, and they enable logging operations such as creating log group, log stream and put a log event in the related log stream.

3. Verify Phone Number

Text message sending can only be possible in case there is a verified phone number under AWS SNS. For this reason, a first a phone number should be added as described below:

  • Search for AWS SNS in the AWS Console
  • Add phone number under the Text messaging section.
  • Add the phone number to be verified and specify the verification language that you can understand
  • The given phone number will receive an SMS message that includes the verification code, which should be entered as shown below.
  • A verified phone number will be listed once this process is completed.

It is noteworthy to emphasize that the account is in sandbox mode and for this service there are some restrictions. AWS claims that SMS sandbox mode enables a secure environment for trying Amazon SNS features without degrading the reputation as an SMS sender. More details are given in this link

4. Implement AWS SMS Lambda

Assuming that all aforementioned steps are completed, you are now ready to send an SMS. A simplified code example is written below. The code receives an JSON message through event object, which inlcudes phone_number, sender, and message. By using sns client, the message is sent. As seen below, the attributes of the SMS such as specifying SENDERIDand SMSTypeare also performed.

import logging
import boto3
def lambda_handler(event, context):
try:
phone_number = event["phone_number"]
sender = event["sender"]
message = event["message"]

client = boto3.client("sns")

# Send the sms message.
response = client.publish(
PhoneNumber=event["phone_number"],
Message=message,
MessageAttributes={
'AWS.SNS.SMS.SenderID': {
'DataType': 'String',
'StringValue': sender
},
'AWS.SNS.SMS.SMSType': {
'DataType': 'String',
'StringValue': 'Promotional'
}
}
)
logging.info("Message ist sent to %s with MessageId %s",
event["phone_number"], response['MessageId'])

print("Message ist sent to %s with MessageId %s",
event["phone_number"], response['MessageId'])
except Exception as e:
logging.error(e)

SenderID depicts the message header, whereas SMSType indicates whether the SMS should be prioritized or not. The following explanations are cited from this link:

  • “Promotional — Non-critical messages, such as marketing messages.”
  • “Transactional — Critical messages that support customer transactions, such as one-time passcodes for multi-factor authentication.”
  • Once the code is ready, it can be added to the Lambda as below and deploy it.

5. Test AWS SMS Lambda & Check CloudWatch Logs

AWS Console in Lambda section provides testing the lambda with the custom data if needed. For the actual use case, a verified phone number, senderID and message are provided to the lambda. Once the message is transmitted, the results can be seen also not only the AWS SNS in the charts but also in the CloudWatch through the added logs.

  • Create a test event
  • Add the message to the Event JSON field and save it.
{
"phone_number":"0000",
"message":"This is the test message for lambda sms!",
"sender":"cosmos",
}
  • Once the test event is executed, it will result below.
  • These results are also added to the CloudWatch
  • Finally, in order to understand whether this lambda works, the given phone number should have received an SMS sent by lambda, and the following SMS screenshot demonstrates the AWS lambda can send the SMS.

Another way of understanding whether the SMS messages are correctly transmitted, Delivery Statistics locating in AWS SNS presents also the successful and unsuccessful sent messages.

Summary

In this tutorial, a simple AWS lambda is implemented that sends SMS through AWS SNS. All required steps are depicted for Sandbox mode. Please remember that AWS SNS has much more usage area such as sending the normal notifications to other services or programs to initiate or trigger them.

--

--