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.
Chilkat Lua Downloads
local chilkat = require("chilkat")
local stringCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
-- Private credentials; do not put this file in public web content or source control.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/sns.json")
if not success then
print("Could not load private SNS credentials.")
return
end
stringCompare:set_string(credentials:string_of("access_key"))
local stringMatch1 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (stringMatch1) then
print("Missing or invalid access_key.")
return
end
stringCompare:set_string(credentials:string_of("secret_key"))
local stringMatch2 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (stringMatch2) then
print("Missing or invalid secret_key.")
return
end
local region = "us-west-2"
local endpoint = chilkat.StringBuilder.new()
endpoint:append("sns.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
local aws = chilkat.AuthAws.new()
aws.access_key = credentials:string_of("access_key")
aws.secret_key = credentials:string_of("secret_key")
aws.region = region
aws.service_name = "sns"
aws.signature_version = 4
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
rest.verbose_logging = false
success = rest:set_auth_aws(aws)
if not success then
print("Could not configure AWS signing.")
return
end
if credentials:has_member("session_token") then
stringCompare:set_string(credentials:string_of("session_token"))
local stringMatch3 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("session_token") ~= 1) or (stringMatch3) then
print("session_token must be a nonempty string when supplied.")
return
end
end
local xml = chilkat.Xml.new()
xml.strict = true
local value = ""
-- Use an authorized recipient in E.164 format; this number is a placeholder.
local phoneNumber = "+15551234567"
local phone = chilkat.StringBuilder.new()
phone:append(phoneNumber)
stringCompare:set_string(phone:get_range(1, 1, false))
local stringMatch4 = stringCompare:contents_equal("0", true)
if (not phone:starts_with("+", true)) or ((phone.length < 2) or ((phone.length > 16) or (stringMatch4))) then
print("Use E.164: + followed by at most 15 digits, starting with a nonzero digit.")
return
end
local digits = chilkat.StringBuilder.new()
digits:append("0123456789")
local position = 1
while position < phone.length do
if not digits:contains(phone:get_range(position, 1, false), true) then
print("Phone number must contain only + and digits.")
return
end
position = position + 1
end
local message = chilkat.StringBuilder.new()
message:append("This is a transactional test message from Amazon SNS.")
if (message.length == 0) or (message.length > 1600) then
print("Use a nonempty SMS message within the 1600-character Publish limit; AWS applies encoding and segmentation rules.")
return
end
-- Explicit certificate verification; keep this Socket alive while Rest uses it.
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS connection failed; inspect diagnostics privately.")
return
end
success = rest:use_connection(connection, true)
if not success then
print("Could not attach TLS connection.")
return
end
success = rest:clear_all_query_params()
if not success then
print("Could not clear parameters from the previous request.")
return
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:add_query_param("Action", "Publish")
if not success then
print("Could not set Action.")
return
end
success = rest:add_query_param("Version", "2010-03-31")
if not success then
print("Could not set Version.")
return
end
-- Include temporary credentials in the signed form body on every request.
if credentials:has_member("session_token") then
success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
if not success then
print("Could not set X-Amz-Security-Token.")
return
end
end
success = rest:add_query_param("PhoneNumber", phoneNumber)
if not success then
print("Could not set PhoneNumber.")
return
end
success = rest:add_query_param_sb("Message", message)
if not success then
print("Could not set SMS message.")
return
end
success = rest:add_query_param("MessageAttributes.entry.1.Name", "AWS.SNS.SMS.SMSType")
if not success then
print("Could not set MessageAttributes.entry.1.Name.")
return
end
success = rest:add_query_param("MessageAttributes.entry.1.Value.DataType", "String")
if not success then
print("Could not set MessageAttributes.entry.1.Value.DataType.")
return
end
success = rest:add_query_param("MessageAttributes.entry.1.Value.StringValue", "Transactional")
if not success then
print("Could not set MessageAttributes.entry.1.Value.StringValue.")
return
end
local responseXml = rest:full_request_form_url_encoded("POST", "/")
if not rest.last_method_success then
print("Request did not complete. Its outcome may be uncertain; reconcile before retrying.")
return
end
success = xml:load_xml(responseXml)
if rest.response_status_code ~= 200 then
print("SNS HTTP status: " .. rest.response_status_code)
if success then
value = xml:get_child_content("Error|Code")
if xml.last_method_success then
print("AWS error code: " .. value)
end
value = xml:get_child_content("RequestId")
if xml.last_method_success then
print("AWS request ID: " .. value)
end
end
-- Full messages, headers, and signing diagnostics may contain private data.
return
end
if not success then
print("Expected a well-formed XML response.")
return
end
stringCompare:set_string(xml.tag)
local stringMatch5 = stringCompare:contents_equal("PublishResponse", true)
if not stringMatch5 then
print("Unexpected SNS response element.")
return
end
value = xml:get_child_content("ResponseMetadata|RequestId")
stringCompare:set_string(value)
local stringMatch6 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch6) then
print("Missing or empty ResponseMetadata|RequestId.")
return
end
print("AWS request ID: " .. value)
value = xml:get_child_content("PublishResult|MessageId")
stringCompare:set_string(value)
local stringMatch7 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch7) then
print("Missing or empty PublishResult|MessageId.")
return
end
print("Message ID: " .. value)
print("SMS accepted by SNS; handset delivery is not confirmed.")