Sending a text message with SNSΒΆ

SNS is AWS’ pub-sub service. It’s useful for sending and receiving alerts for events you care about. It can also be used to send SMS messages. If you’ve setup your AWS command-line tool, you can do this in 3 lines of Python.

import boto3
sns = boto3.client('sns')
sns.publish(
   PhoneNumber='+15558675309',
   Message='hello world'
)

You should get a response dictionary back.

{'MessageId': 'c58ef7a6-c730-5aac-9292-a697b5c469e2',
'ResponseMetadata': {'HTTPHeaders': {'content-length': '294',
  'content-type': 'text/xml',
  'date': 'Thu, 02 Mar 2017 01:09:08 GMT',
  'x-amzn-requestid': 'abf21d3f-c96e-5a66-8e08-4c0ebb9af928'},
 'HTTPStatusCode': 200,
 'RequestId': 'abf21d3f-c96e-5a66-8e08-4c0ebb9af928',
 'RetryAttempts': 0}}

And a few seconds later, your text message will go through.

text message

That’s all there is to it.

NOTE: if you get an AccessDenied error, you need to give yourself Publish access in SNS. Here’s a custom policy you can use.

{
   "Version": "2012-10-17",
   "Statement": [
       {
           "Sid": "Stmt1488417906000",
           "Effect": "Allow",
           "Action": [
               "sns:Publish"
           ],
           "Resource": [
               "*"
           ]
       }
   ]
}

Make sure to read about IAM policies if that doesn’t make sense.

Comments

comments powered by Disqus