6

How does one send sms directly to the mobile number via AWS SNS using boto (or other python|perl library) ?

Constraints:

  • without using AWS Lambda functions
  • without using SNS topics to subscribe mobile numbers directly

My use case: sending SMS alerts from Nagios using AWS SNS using AWS SMS as the endpoint protocol.

1
  • You don't need lambda or SNS topics, and there is an example in the doc, it's in Java but quite easy to translate. Commented Nov 25, 2016 at 10:11

4 Answers 4

13

Here's the code to publish directly to a phone number via SNS using boto3. If you get an error regarding the PhoneNumber parameter, you'll need to upgrade your version boto. It's important to remember that SNS currently supports direct publish to a phone number (PhoneNumber) or push notifications endpoint (targetArn). Also note that TopicArn, PhoneNumber, and TargetArn are all mutually exclusive and therefore you can only specify one of these per publish.

import boto3

sns_client = boto3.client('sns')

response = sns_client.publish(
    PhoneNumber='+12065551212', 
    Message='This is a test SMS message',
    #TopicArn='string', (Optional - can't be used with PhoneNumer)
    #TargetArn='string', (Optional - can't be used with PhoneNumer)
    #Subject='string', (Optional - not used with PhoneNumer)
    #MessageStructure='string' (Optional)
)

print(response)
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Dennis, I tried your code but ended up with the following error: raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (OptInRequired) when calling the Publish operation: The AWS Access Key Id needs a subscription for the service
I know I am missing out on some permission, but I have already added SNSFull access permission for this user. Is there anything in addition to this that has to be done?
@dennis-aws I tried this method. I got HttpStatus as 200 but didn't got any text message on the mobile. Any suggestions ?
4

The below script is working for me just replace the required parameters that are defined as constants in the script. The below script also handles bulk SMS to multiple recipients

import json
import boto3
import os


ACCESS_KEY = <your key>
ACCESS_SECRET = <your secret>
AWS_REGION = <your region>

RECIPIENT_NUMBERS = [<recipient number list>]
SENDER_ID = <sender_id>
MESSAGE = <your message>

sns = boto3.client('sns', aws_access_key_id=ACCESS_KEY,
               aws_secret_access_key=ACCESS_SECRET,
               region_name=AWS_REGION)
for number in RECIPIENT_NUMBERS:
    response = sns.publish(
        PhoneNumber=number,
        Message=MESSAGE,
        MessageAttributes={
            'AWS.SNS.SMS.SenderID': {'DataType': 'String',
                                 'StringValue': SENDER_ID},
            'AWS.SNS.SMS.SMSType': {'DataType': 'String',
                                'StringValue': 'Promotional'}
        }
    )
    print(response)

Comments

2

Just replace in required fields, you will get this working.

import boto3
# Create an SNS client
client = boto3.client(
    "sns",
    aws_access_key_id="your_access_key_id",
    aws_secret_access_key="you_secret_access_key",
    region_name="us-east-1"
)

# Send your sms message.
client.publish(
    PhoneNumber="your_phone_number",
    Message="Hello World!"
)

For sending to multiple contacts, refer here

Comments

-1
#!/usr/bin/python
#sns to sms notification script.
import datetime
import boto3
import sys
body=[]
log_file="/var/log/sns2sms.log"
logf=open(log_file,"a")
mobile_number=str(sys.argv[1])
subject=str(sys.argv[2])
body.append(subject)
for line in sys.stdin:
 body.append(line)
 message_body="\n".join(body)
 now = str(datetime.datetime.now())
 log_string=now+" "+mobile_number+" "+message_body+" "
client = boto3.client('sns')
client.publish(
 PhoneNumber = mobile_number,
 Message = message_body
)
logf.write(log_string)
logf.write("\n")
logf.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.