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

Amazon SNS: Subscribe an Email Address (Confirmation Required)

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.

Subscribes an endpoint to a standard topic. The sample explicitly requests ReturnSubscriptionArn=false and distinguishes the literal pending confirmation from a returned ARN. Email recipients must follow the confirmation workflow; an accepted Subscribe request does not prove confirmation or delivery. Do not bypass endpoint-owner confirmation. Email/SMS are not FIFO-topic subscription protocols.

Use a recipient address you are authorized to subscribe. SNS sends a confirmation email; the confirmation token remains valid for two days. This example does not retrieve or automatically follow confirmation links. Cross-account subscriptions can also require endpoint-owner confirmation.

Required IAM action: sns:Subscribe. 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 Subscribe reference

Chilkat VBScript Downloads

VBScript
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)

success = 0

set stringCompare = CreateObject("Chilkat.StringBuilder")
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  Private credentials; do not put this file in public web content or source control.
set credentials = CreateObject("Chilkat.JsonObject")
credentials.Strict = 1
success = credentials.LoadFile("qa_data/aws/sns.json")
If (success <> 1) Then
    outFile.WriteLine("Could not load private SNS credentials.")
    WScript.Quit
End If

success = stringCompare.SetString(credentials.StringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = 1)) Then
    outFile.WriteLine("Missing or invalid access_key.")
    WScript.Quit
End If

success = stringCompare.SetString(credentials.StringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = 1)) Then
    outFile.WriteLine("Missing or invalid secret_key.")
    WScript.Quit
End If

region = "us-west-2"
set endpoint = CreateObject("Chilkat.StringBuilder")
success = endpoint.Append("sns.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
set aws = CreateObject("Chilkat.AuthAws")
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "sns"
aws.SignatureVersion = 4
set rest = CreateObject("Chilkat.Rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = 0
success = rest.SetAuthAws(aws)
If (success <> 1) Then
    outFile.WriteLine("Could not configure AWS signing.")
    WScript.Quit
End If

If (credentials.HasMember("session_token") = 1) Then
    success = stringCompare.SetString(credentials.StringOf("session_token"))
    stringMatch3 = stringCompare.ContentsEqual("",1)
    If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = 1)) Then
        outFile.WriteLine("session_token must be a nonempty string when supplied.")
        WScript.Quit
    End If

End If

set xml = CreateObject("Chilkat.Xml")
xml.Strict = 1

topicArn = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
set topic = CreateObject("Chilkat.StringBuilder")
success = topic.Append(topicArn)
set arnPrefix = CreateObject("Chilkat.StringBuilder")
success = arnPrefix.Append("arn:aws:sns:")
success = arnPrefix.Append(region)
success = arnPrefix.Append(":")
If (topic.StartsWith(arnPrefix.GetAsString(),1) <> 1) Then
    outFile.WriteLine("Select an SNS topic ARN in the configured region and commercial AWS partition.")
    WScript.Quit
End If

If (topic.EndsWith(".fifo",1) = 1) Then
    outFile.WriteLine("This example uses a standard topic. FIFO publishing needs group/deduplication handling.")
    WScript.Quit
End If

emailAddress = "recipient@example.com"
'  Explicit certificate verification; keep this Socket alive while Rest uses it.
set connection = CreateObject("Chilkat.Socket")
connection.RequireSslCertVerify = 1
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,1,20000)
If (success <> 1) Then
    outFile.WriteLine("TLS connection failed; inspect diagnostics privately.")
    WScript.Quit
End If

success = rest.UseConnection(connection,1)
If (success <> 1) Then
    outFile.WriteLine("Could not attach TLS connection.")
    WScript.Quit
End If

success = rest.ClearAllQueryParams()
If (success <> 1) Then
    outFile.WriteLine("Could not clear parameters from the previous request.")
    WScript.Quit
End If

'  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","Subscribe")
If (success <> 1) Then
    outFile.WriteLine("Could not set Action.")
    WScript.Quit
End If

success = rest.AddQueryParam("Version","2010-03-31")
If (success <> 1) Then
    outFile.WriteLine("Could not set Version.")
    WScript.Quit
End If

'  Include temporary credentials in the signed form body on every request.
If (credentials.HasMember("session_token") = 1) Then
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
    If (success <> 1) Then
        outFile.WriteLine("Could not set X-Amz-Security-Token.")
        WScript.Quit
    End If

End If

success = rest.AddQueryParam("TopicArn",topicArn)
If (success <> 1) Then
    outFile.WriteLine("Could not set TopicArn.")
    WScript.Quit
End If

success = rest.AddQueryParam("Protocol","email")
If (success <> 1) Then
    outFile.WriteLine("Could not set Protocol.")
    WScript.Quit
End If

success = rest.AddQueryParam("Endpoint",emailAddress)
If (success <> 1) Then
    outFile.WriteLine("Could not set Endpoint.")
    WScript.Quit
End If

success = rest.AddQueryParam("ReturnSubscriptionArn","false")
If (success <> 1) Then
    outFile.WriteLine("Could not set ReturnSubscriptionArn.")
    WScript.Quit
End If

responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> 1) Then
    outFile.WriteLine("Request did not complete. Its outcome may be uncertain; reconcile before retrying.")
    WScript.Quit
End If

success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
    outFile.WriteLine("SNS HTTP status: " & rest.ResponseStatusCode)
    If (success = 1) Then
        value = xml.GetChildContent("Error|Code")
        If (xml.LastMethodSuccess = 1) Then
            outFile.WriteLine("AWS error code: " & value)
        End If

        value = xml.GetChildContent("RequestId")
        If (xml.LastMethodSuccess = 1) Then
            outFile.WriteLine("AWS request ID: " & value)
        End If

    End If

    '  Full messages, headers, and signing diagnostics may contain private data.
    WScript.Quit
End If

If (success <> 1) Then
    outFile.WriteLine("Expected a well-formed XML response.")
    WScript.Quit
End If

success = stringCompare.SetString(xml.Tag)
stringMatch4 = stringCompare.ContentsEqual("SubscribeResponse",1)
If (stringMatch4 <> 1) Then
    outFile.WriteLine("Unexpected SNS response element.")
    WScript.Quit
End If

value = xml.GetChildContent("ResponseMetadata|RequestId")
success = stringCompare.SetString(value)
stringMatch5 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch5 = 1)) Then
    outFile.WriteLine("Missing or empty ResponseMetadata|RequestId.")
    WScript.Quit
End If

outFile.WriteLine("AWS request ID: " & value)
value = xml.GetChildContent("SubscribeResult|SubscriptionArn")
success = stringCompare.SetString(value)
stringMatch6 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch6 = 1)) Then
    outFile.WriteLine("Missing or empty SubscribeResult|SubscriptionArn.")
    WScript.Quit
End If

success = stringCompare.SetString(value)
stringMatch7 = stringCompare.ContentsEqual("pending confirmation",1)
If (stringMatch7 = 1) Then
    outFile.WriteLine("Subscription is pending confirmation; delivery is not active yet.")
Else
    outFile.WriteLine("Subscription ARN: " & value)
    outFile.WriteLine("Subscription request succeeded.")
End If


outFile.Close