Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.6.0+

Amazon SNS: Send an SMS Directly to an E.164 Phone Number

See more Amazon SNS Examples

Uses the current Amazon SNS Query API (Version=2010-03-31) through Chilkat.Rest and AuthAws, with HTTPS, Signature Version 4, and service sns. The API version date remains current. Action and input parameters are URL-encoded into a POST body, avoiding message text and recipient addresses in the URL. Set the actual region once; other AWS partitions need their documented endpoint suffix and ARN partition.

Load private qa_data/aws/sns.json with nonempty string fields access_key, secret_key, and session_token when using temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles, obtain credentials, or refresh them automatically. The session token is included in the signed form body on every request. A Socket explicitly enables TLS certificate verification before passing the connection to Rest.

Checks setup calls, transport completion, HTTP status, XML parsing, result root, and required fields. Normal output includes identifiers, not full messages or headers. Keep detailed diagnostics private. For retryable failures, use bounded backoff with jitter in the application; these examples do not automatically retry writes. A Publish timeout can leave an accepted message and retrying a standard-topic/SMS publish can duplicate it. A returned MessageId confirms SNS acceptance, not subscriber or handset delivery.

Use an authorized recipient in E.164 format. New SMS accounts start in the regional SMS sandbox and can send only to verified destinations. Origination identities, country support, registration, spending limits and opt-out status can affect delivery. Confirm the appropriate configuration with SNS SMS sandbox guidance and SNS SMS sending guidance.

Messages can be segmented and billed as multiple SMS messages; encoding affects segment size. The sample chooses AWS.SNS.SMS.SMSType=Transactional for a transactional test message; choose a type appropriate to the actual use. A MessageId is not a delivery receipt. Direct SMS uses PhoneNumber without TopicArn or TargetArn. There is no need to create a topic or subscription for a direct send.

The local input check limits the message to 1,600 characters but does not predict segment count or cost. The example sets only PhoneNumber as its destination; it does not publish to a topic at the same time.

Required IAM action: sns:Publish. Grant only the intended resource access; direct SMS does not have a topic ARN resource. Topic policies and KMS key access can also affect requests.

AWS Publish reference

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Private credentials; do not put this file in public web content or source control.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/sns.json")
if (success != true)
    print "Could not load private SNS credentials." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == true))
    print "Missing or invalid access_key." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == true))
    print "Missing or invalid secret_key." + "\n";
    exit
end

region = "us-west-2"
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("sns.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = Chilkat::CkAuthAws.new()
aws.put_AccessKey(credentials.stringOf("access_key"))
aws.put_SecretKey(credentials.stringOf("secret_key"))
aws.put_Region(region)
aws.put_ServiceName("sns")
aws.put_SignatureVersion(4)
rest = Chilkat::CkRest.new()
rest.put_ConnectTimeoutMs(20000)
rest.put_IdleTimeoutMs(60000)
rest.put_VerboseLogging(false)
success = rest.SetAuthAws(aws)
if (success != true)
    print "Could not configure AWS signing." + "\n";
    exit
end

if (credentials.HasMember("session_token") == true)
    stringCompare.SetString(credentials.stringOf("session_token"))
    stringMatch3 = stringCompare.ContentsEqual("",true)
    if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == true))
        print "session_token must be a nonempty string when supplied." + "\n";
        exit
    end

end

xml = Chilkat::CkXml.new()
xml.put_Strict(true)

#  Use an authorized recipient in E.164 format; this number is a placeholder.
phoneNumber = "+15551234567"
phone = Chilkat::CkStringBuilder.new()
phone.Append(phoneNumber)
stringCompare.SetString(phone.getRange(1,1,false))
stringMatch4 = stringCompare.ContentsEqual("0",true)
if ((phone.StartsWith("+",true) != true) or (phone.get_Length() < 2) or (phone.get_Length() > 16) or (stringMatch4 == true))
    print "Use E.164: + followed by at most 15 digits, starting with a nonzero digit." + "\n";
    exit
end

digits = Chilkat::CkStringBuilder.new()
digits.Append("0123456789")
position = 1
while (position < phone.get_Length())
    if (digits.Contains(phone.getRange(position,1,false),true) != true)
        print "Phone number must contain only + and digits." + "\n";
        exit
    end

    position = position + 1
end
message = Chilkat::CkStringBuilder.new()
message.Append("This is a transactional test message from Amazon SNS.")
if ((message.get_Length() == 0) or (message.get_Length() > 1600))
    print "Use a nonempty SMS message within the 1600-character Publish limit; AWS applies encoding and segmentation rules." + "\n";
    exit
end

#  Explicit certificate verification; keep this Socket alive while Rest uses it.
connection = Chilkat::CkSocket.new()
connection.put_RequireSslCertVerify(true)
connection.put_MaxReadIdleMs(60000)
connection.put_MaxSendIdleMs(60000)
success = connection.Connect(endpoint.getAsString(),443,true,20000)
if (success != true)
    print "TLS connection failed; inspect diagnostics privately." + "\n";
    exit
end

success = rest.UseConnection(connection,true)
if (success != true)
    print "Could not attach TLS connection." + "\n";
    exit
end

success = rest.ClearAllQueryParams()
if (success != true)
    print "Could not clear parameters from the previous request." + "\n";
    exit
end

#  Build a fresh form for each request; do not retain previous parameters.
#  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
success = rest.AddQueryParam("Action","Publish")
if (success != true)
    print "Could not set Action." + "\n";
    exit
end

success = rest.AddQueryParam("Version","2010-03-31")
if (success != true)
    print "Could not set Version." + "\n";
    exit
end

#  Include temporary credentials in the signed form body on every request.
if (credentials.HasMember("session_token") == true)
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"))
    if (success != true)
        print "Could not set X-Amz-Security-Token." + "\n";
        exit
    end

end

success = rest.AddQueryParam("PhoneNumber",phoneNumber)
if (success != true)
    print "Could not set PhoneNumber." + "\n";
    exit
end

success = rest.AddQueryParamSb("Message",message)
if (success != true)
    print "Could not set SMS message." + "\n";
    exit
end

success = rest.AddQueryParam("MessageAttributes.entry.1.Name","AWS.SNS.SMS.SMSType")
if (success != true)
    print "Could not set MessageAttributes.entry.1.Name." + "\n";
    exit
end

success = rest.AddQueryParam("MessageAttributes.entry.1.Value.DataType","String")
if (success != true)
    print "Could not set MessageAttributes.entry.1.Value.DataType." + "\n";
    exit
end

success = rest.AddQueryParam("MessageAttributes.entry.1.Value.StringValue","Transactional")
if (success != true)
    print "Could not set MessageAttributes.entry.1.Value.StringValue." + "\n";
    exit
end

responseXml = rest.fullRequestFormUrlEncoded("POST","/")
if (rest.get_LastMethodSuccess() != true)
    print "Request did not complete. Its outcome may be uncertain; reconcile before retrying." + "\n";
    exit
end

success = xml.LoadXml(responseXml)
if (rest.get_ResponseStatusCode() != 200)
    print "SNS HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    if (success == true)
        value = xml.getChildContent("Error|Code")
        if (xml.get_LastMethodSuccess() == true)
            print "AWS error code: " + value + "\n";
        end

        value = xml.getChildContent("RequestId")
        if (xml.get_LastMethodSuccess() == true)
            print "AWS request ID: " + value + "\n";
        end

    end

    #  Full messages, headers, and signing diagnostics may contain private data.
    exit
end

if (success != true)
    print "Expected a well-formed XML response." + "\n";
    exit
end

stringCompare.SetString(xml.tag())
stringMatch5 = stringCompare.ContentsEqual("PublishResponse",true)
if (stringMatch5 != true)
    print "Unexpected SNS response element." + "\n";
    exit
end

value = xml.getChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
stringMatch6 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch6 == true))
    print "Missing or empty ResponseMetadata|RequestId." + "\n";
    exit
end

print "AWS request ID: " + value + "\n";
value = xml.getChildContent("PublishResult|MessageId")
stringCompare.SetString(value)
stringMatch7 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch7 == true))
    print "Missing or empty PublishResult|MessageId." + "\n";
    exit
end

print "Message ID: " + value + "\n";
print "SMS accepted by SNS; handset delivery is not confirmed." + "\n";