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

Amazon SNS: Send Korean, Chinese, or Japanese SMS from a UTF-8 File

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.

Reads qa_data/txt/hello_korean_chinese_japanese.txt as UTF-8 and checks LoadFile before sending. Unicode characters are form-encoded exactly once; no manual URL escaping is needed. The local character check is an input bound, not a GSM/UCS-2 segment or cost estimator. SNS and downstream providers determine encoding eligibility and segmentation. Verbose logging is disabled and message text is not printed.

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 Delphi ActiveX Downloads

Delphi ActiveX
var
success: Integer;
stringCompare: TChilkatStringBuilder;
credentials: TChilkatJsonObject;
stringMatch1: Integer;
stringMatch2: Integer;
region: WideString;
endpoint: TChilkatStringBuilder;
aws: TChilkatAuthAws;
rest: TChilkatRest;
stringMatch3: Integer;
xml: TChilkatXml;
value: WideString;
phoneNumber: WideString;
phone: TChilkatStringBuilder;
stringMatch4: Integer;
digits: TChilkatStringBuilder;
position: Integer;
message: TChilkatStringBuilder;
connection: TChilkatSocket;
responseXml: WideString;
stringMatch5: Integer;
stringMatch6: Integer;
stringMatch7: Integer;

begin
success := 0;

stringCompare := TChilkatStringBuilder.Create(Self);
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Private credentials; do not put this file in public web content or source control.
credentials := TChilkatJsonObject.Create(Self);
credentials.Strict := 1;
success := credentials.LoadFile('qa_data/aws/sns.json');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not load private SNS credentials.');
    Exit;
  end;
stringCompare.SetString(credentials.StringOf('access_key'));
stringMatch1 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('access_key') <> 1) or (stringMatch1 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
stringCompare.SetString(credentials.StringOf('secret_key'));
stringMatch2 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('secret_key') <> 1) or (stringMatch2 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
region := 'us-west-2';
endpoint := TChilkatStringBuilder.Create(Self);
endpoint.Append('sns.');
endpoint.Append(region);
endpoint.Append('.amazonaws.com');
aws := TChilkatAuthAws.Create(Self);
aws.AccessKey := credentials.StringOf('access_key');
aws.SecretKey := credentials.StringOf('secret_key');
aws.Region := region;
aws.ServiceName := 'sns';
aws.SignatureVersion := 4;
rest := TChilkatRest.Create(Self);
rest.ConnectTimeoutMs := 20000;
rest.IdleTimeoutMs := 60000;
rest.VerboseLogging := 0;
success := rest.SetAuthAws(aws.ControlInterface);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not configure AWS signing.');
    Exit;
  end;
if (credentials.HasMember('session_token') = 1) then
  begin
    stringCompare.SetString(credentials.StringOf('session_token'));
    stringMatch3 := stringCompare.ContentsEqual('',1);
    if ((credentials.JsonTypeOf('session_token') <> 1) or (stringMatch3 = 1)) then
      begin
        Memo1.Lines.Add('session_token must be a nonempty string when supplied.');
        Exit;
      end;
  end;
xml := TChilkatXml.Create(Self);
xml.Strict := 1;

//  Use an authorized recipient in E.164 format; this number is a placeholder.
phoneNumber := '+15551234567';
phone := TChilkatStringBuilder.Create(Self);
phone.Append(phoneNumber);
stringCompare.SetString(phone.GetRange(1,1,0));
stringMatch4 := stringCompare.ContentsEqual('0',1);
if ((phone.StartsWith('+',1) <> 1) or (phone.Length < 2) or (phone.Length > 16) or (stringMatch4 = 1)) then
  begin
    Memo1.Lines.Add('Use E.164: + followed by at most 15 digits, starting with a nonzero digit.');
    Exit;
  end;
digits := TChilkatStringBuilder.Create(Self);
digits.Append('0123456789');
position := 1;
while (position < phone.Length) do
  begin
    if (digits.Contains(phone.GetRange(position,1,0),1) <> 1) then
      begin
        Memo1.Lines.Add('Phone number must contain only + and digits.');
        Exit;
      end;
    position := position + 1;
  end;

message := TChilkatStringBuilder.Create(Self);
success := message.LoadFile('qa_data/txt/hello_korean_chinese_japanese.txt','utf-8');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not read the UTF-8 message file.');
    Exit;
  end;
if ((message.Length = 0) or (message.Length > 1600)) then
  begin
    Memo1.Lines.Add('Use a nonempty SMS message within the 1600-character Publish limit; AWS applies encoding and segmentation rules.');
    Exit;
  end;
//  Explicit certificate verification; keep this Socket alive while Rest uses it.
connection := TChilkatSocket.Create(Self);
connection.RequireSslCertVerify := 1;
connection.MaxReadIdleMs := 60000;
connection.MaxSendIdleMs := 60000;
success := connection.Connect(endpoint.GetAsString(),443,1,20000);
if (success <> 1) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := rest.UseConnection(connection.ControlInterface,1);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not attach TLS connection.');
    Exit;
  end;
success := rest.ClearAllQueryParams();
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not clear parameters from the previous request.');
    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 <> 1) then
  begin
    Memo1.Lines.Add('Could not set Action.');
    Exit;
  end;
success := rest.AddQueryParam('Version','2010-03-31');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set Version.');
    Exit;
  end;
//  Include temporary credentials in the signed form body on every request.
if (credentials.HasMember('session_token') = 1) then
  begin
    success := rest.AddQueryParam('X-Amz-Security-Token',credentials.StringOf('session_token'));
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not set X-Amz-Security-Token.');
        Exit;
      end;
  end;
success := rest.AddQueryParam('PhoneNumber',phoneNumber);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set PhoneNumber.');
    Exit;
  end;
success := rest.AddQueryParamSb('Message',message.ControlInterface);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set SMS message.');
    Exit;
  end;
success := rest.AddQueryParam('MessageAttributes.entry.1.Name','AWS.SNS.SMS.SMSType');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set MessageAttributes.entry.1.Name.');
    Exit;
  end;
success := rest.AddQueryParam('MessageAttributes.entry.1.Value.DataType','String');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set MessageAttributes.entry.1.Value.DataType.');
    Exit;
  end;
success := rest.AddQueryParam('MessageAttributes.entry.1.Value.StringValue','Transactional');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set MessageAttributes.entry.1.Value.StringValue.');
    Exit;
  end;
responseXml := rest.FullRequestFormUrlEncoded('POST','/');
if (rest.LastMethodSuccess <> 1) then
  begin
    Memo1.Lines.Add('Request did not complete. Its outcome may be uncertain; reconcile before retrying.');
    Exit;
  end;
success := xml.LoadXml(responseXml);
if (rest.ResponseStatusCode <> 200) then
  begin
    Memo1.Lines.Add('SNS HTTP status: ' + IntToStr(rest.ResponseStatusCode));
    if (success = 1) then
      begin
        value := xml.GetChildContent('Error|Code');
        if (xml.LastMethodSuccess = 1) then
          begin
            Memo1.Lines.Add('AWS error code: ' + value);
          end;
        value := xml.GetChildContent('RequestId');
        if (xml.LastMethodSuccess = 1) then
          begin
            Memo1.Lines.Add('AWS request ID: ' + value);
          end;
      end;
    //  Full messages, headers, and signing diagnostics may contain private data.
    Exit;
  end;
if (success <> 1) then
  begin
    Memo1.Lines.Add('Expected a well-formed XML response.');
    Exit;
  end;
stringCompare.SetString(xml.Tag);
stringMatch5 := stringCompare.ContentsEqual('PublishResponse',1);
if (stringMatch5 <> 1) then
  begin
    Memo1.Lines.Add('Unexpected SNS response element.');
    Exit;
  end;
value := xml.GetChildContent('ResponseMetadata|RequestId');
stringCompare.SetString(value);
stringMatch6 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch6 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
    Exit;
  end;
Memo1.Lines.Add('AWS request ID: ' + value);
value := xml.GetChildContent('PublishResult|MessageId');
stringCompare.SetString(value);
stringMatch7 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch7 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty PublishResult|MessageId.');
    Exit;
  end;
Memo1.Lines.Add('Message ID: ' + value);
Memo1.Lines.Add('SMS accepted by SNS; handset delivery is not confirmed.');