Chilkat Online Tools

Node.js / Twilio Messaging / SMS / Send an SMS

Back to Collection Items

var os = require('os');
if (os.platform() == 'win32') {  
    if (os.arch() == 'ia32') {
        var chilkat = require('@chilkat/ck-node21-win-ia32');
    } else {
        var chilkat = require('@chilkat/ck-node21-win64'); 
    }
} else if (os.platform() == 'linux') {
    if (os.arch() == 'arm') {
        var chilkat = require('@chilkat/ck-node21-arm');
    } else if (os.arch() == 'x86') {
        var chilkat = require('@chilkat/ck-node21-linux32');
    } else {
        var chilkat = require('@chilkat/ck-node21-linux64');
    }
} else if (os.platform() == 'darwin') {
    if (os.arch() == 'arm64') {
        var chilkat = require('@chilkat/ck-node21-mac-m1');
    } else {
        var chilkat = require('@chilkat/ck-node21-macosx');
    }
}


function chilkatExample() {

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    var http = new chilkat.Http();
    var success;

    http.BasicAuth = true;
    http.Login = "{{TWILIO_ACCOUNT_SID}}";
    http.Password = "{{TWILIO_AUTH_TOKEN}}";

    var req = new chilkat.HttpRequest();
    req.AddParam("Body","Hello World!");

    var jsonParam2 = new chilkat.JsonObject();
    req.AddParam("To",jsonParam2.Emit());

    var jsonParam3 = new chilkat.JsonObject();
    req.AddParam("From",jsonParam3.Emit());

    // resp: HttpResponse
    var resp = http.PostUrlEncoded("https://api.twilio.com/2010-04-01/Accounts/:AccountSid/Messages.json",req);
    if (http.LastMethodSuccess == false) {
        console.log(http.LastErrorText);
        return;
    }

    var sbResponseBody = new chilkat.StringBuilder();
    resp.GetBodySb(sbResponseBody);

    var jResp = new chilkat.JsonObject();
    jResp.LoadSb(sbResponseBody);
    jResp.EmitCompact = false;

    console.log("Response Body:");
    console.log(jResp.Emit());

    var respStatusCode = resp.StatusCode;
    console.log("Response Status Code = " + respStatusCode);
    if (respStatusCode >= 400) {
        console.log("Response Header:");
        console.log(resp.Header);
        console.log("Failed.");

        return;
    }

    // Sample JSON response:
    // (Sample code for parsing the JSON response is shown below)

    // {
    //   "account_sid": "ACF8",
    //   "api_version": "exercitation eiusmod amet laboris",
    //   "body": "consectetur exercitation officia magna",
    //   "date_created": "consectetur exercitation proident",
    //   "date_sent": "culpa sint labore",
    //   "date_updated": "proident",
    //   "direction": "outbound-call",
    //   "error_code": -64742646,
    //   "error_message": "nostrud sint Ut",
    //   "from": "Excepteur cillum aute",
    //   "messaging_service_sid": "MGDB",
    //   "num_media": "dolor veniam non",
    //   "num_segments": "et ut sint ut amet",
    //   "price": "Lorem reprehenderit",
    //   "price_unit": "Excepteur tempor i",
    //   "sid": "MM79",
    //   "status": "received",
    //   "subresource_uris": {},
    //   "to": "Ut non id",
    //   "uri": "magna sit esse"
    // }

    // Sample code for parsing the JSON response...
    // Use this online tool to generate parsing code from sample JSON: Generate JSON Parsing Code

    var date_created = new chilkat.DtObj();
    var date_sent = new chilkat.DtObj();
    var date_updated = new chilkat.DtObj();

    var account_sid = jResp.StringOf("account_sid");
    var api_version = jResp.StringOf("api_version");
    var body = jResp.StringOf("body");
    jResp.DtOf("date_created",false,date_created);
    jResp.DtOf("date_sent",false,date_sent);
    jResp.DtOf("date_updated",false,date_updated);
    var direction = jResp.StringOf("direction");
    var error_code = jResp.IntOf("error_code");
    var error_message = jResp.StringOf("error_message");
    var from = jResp.StringOf("from");
    var messaging_service_sid = jResp.StringOf("messaging_service_sid");
    var num_media = jResp.StringOf("num_media");
    var num_segments = jResp.StringOf("num_segments");
    var price = jResp.StringOf("price");
    var price_unit = jResp.StringOf("price_unit");
    var sid = jResp.StringOf("sid");
    var status = jResp.StringOf("status");
    var v_to = jResp.StringOf("to");
    var uri = jResp.StringOf("uri");

}

chilkatExample();

Curl Command

curl -X POST
	-u '{{TWILIO_ACCOUNT_SID}}:{{TWILIO_AUTH_TOKEN}}'
	-H "Content-Type: application/x-www-form-urlencoded"
	--data-urlencode 'Body=Hello World!'
	--data-urlencode 'To={{MY_PHONE_NUMBER}}'
	--data-urlencode 'From={{TWILIO_PHONE_NUMBER}}'
https://api.twilio.com/2010-04-01/Accounts/:AccountSid/Messages.json

Postman Collection Item JSON

{
  "name": "Send an SMS",
  "request": {
    "auth": {
      "type": "basic",
      "basic": [
        {
          "key": "password",
          "value": "{{TWILIO_AUTH_TOKEN}}",
          "type": "string"
        },
        {
          "key": "username",
          "value": "{{TWILIO_ACCOUNT_SID}}",
          "type": "string"
        }
      ]
    },
    "method": "POST",
    "header": [
      {
        "key": "Content-Type",
        "value": "application/x-www-form-urlencoded"
      }
    ],
    "body": {
      "mode": "urlencoded",
      "urlencoded": [
        {
          "key": "Body",
          "value": "Hello World!",
          "description": "The text of the message you want to send. Can be up to 1,600 characters in length."
        },
        {
          "key": "To",
          "value": "{{MY_PHONE_NUMBER}}",
          "description": "The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format for SMS/MMS or [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses) for other 3rd-party channels."
        },
        {
          "key": "From",
          "value": "{{TWILIO_PHONE_NUMBER}}",
          "description": "A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, an [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses) that is enabled for the type of message you want to send. Phone numbers or [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from Twilio also work here. You cannot, for example, spoof messages from a private cell phone number. If you are using `messaging_service_sid`, this parameter must be empty."
        },
        {
          "key": "AddressRetention",
          "value": "<string>",
          "description": "Determines if the address can be stored or obfuscated based on privacy settings (This can only be one of retain)",
          "disabled": true
        },
        {
          "key": "ApplicationSid",
          "value": "<string>",
          "description": "The SID of the application that should receive message status. We POST a `message_sid` parameter and a `message_status` parameter with a value of `sent` or `failed` to the [application](https://www.twilio.com/docs/usage/api/applications)'s `message_status_callback`. If a `status_callback` parameter is also passed, it will be ignored and the application's `message_status_callback` parameter will be used.",
          "disabled": true
        },
        {
          "key": "Attempt",
          "value": "<integer>",
          "description": "Total number of attempts made ( including this ) to send out the message regardless of the provider used",
          "disabled": true
        },
        {
          "key": "ContentRetention",
          "value": "<string>",
          "description": "Determines if the message content can be stored or redacted based on privacy settings (This can only be one of retain)",
          "disabled": true
        },
        {
          "key": "ForceDelivery",
          "value": "<boolean>",
          "description": "Reserved",
          "disabled": true
        },
        {
          "key": "MaxPrice",
          "value": "<number>",
          "description": "The maximum total price in US dollars that you will pay for the message to be delivered. Can be a decimal value that has up to 4 decimal places. All messages are queued for delivery and the message cost is checked before the message is sent. If the cost exceeds `max_price`, the message will fail and a status of `Failed` is sent to the status callback. If `MaxPrice` is not set, the message cost is not checked.",
          "disabled": true
        },
        {
          "key": "MediaUrl",
          "value": "[\"<uri>\",\"<uri>\"]",
          "description": "The URL of the media to send with the message. The media can be of type `gif`, `png`, and `jpeg` and will be formatted correctly on the recipient's device. The media size limit is 5MB for supported file types (JPEG, PNG, GIF) and 500KB for [other types](https://www.twilio.com/docs/sms/accepted-mime-types) of accepted media. To send more than one image in the message body, provide multiple `media_url` parameters in the POST request. You can include up to 10 `media_url` parameters per message. You can send images in an SMS message in only the US and Canada.",
          "disabled": true
        },
        {
          "key": "MessagingServiceSid",
          "value": "<string>",
          "description": "The SID of the [Messaging Service](https://www.twilio.com/docs/sms/services#send-a-message-with-copilot) you want to associate with the Message. Set this parameter to use the [Messaging Service Settings and Copilot Features](https://www.twilio.com/console/sms/services) you have configured and leave the `from` parameter empty. When only this parameter is set, Twilio will use your enabled Copilot Features to select the `from` phone number for delivery.",
          "disabled": true
        },
        {
          "key": "PersistentAction",
          "value": "[\"<string>\",\"<string>\"]",
          "description": "Rich actions for Channels Messages.",
          "disabled": true
        },
        {
          "key": "ProvideFeedback",
          "value": "<boolean>",
          "description": "Whether to confirm delivery of the message. Set this value to `true` if you are sending messages that have a trackable user action and you intend to confirm delivery of the message using the [Message Feedback API](https://www.twilio.com/docs/sms/api/message-feedback-resource). This parameter is `false` by default.",
          "disabled": true
        },
        {
          "key": "SmartEncoded",
          "value": "<boolean>",
          "description": "Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`.",
          "disabled": true
        },
        {
          "key": "StatusCallback",
          "value": "<uri>",
          "description": "The URL we should call using the `status_callback_method` to send status information to your application. If specified, we POST these message status changes to the URL: `queued`, `failed`, `sent`, `delivered`, or `undelivered`. Twilio will POST its [standard request parameters](https://www.twilio.com/docs/sms/twiml#request-parameters) as well as some additional parameters including `MessageSid`, `MessageStatus`, and `ErrorCode`. If you include this parameter with the `messaging_service_sid`, we use this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/sms/services/api). URLs must contain a valid hostname and underscores are not allowed.",
          "disabled": true
        },
        {
          "key": "ValidityPeriod",
          "value": "<integer>",
          "description": "How long in seconds the message can remain in our outgoing message queue. After this period elapses, the message fails and we call your status callback. Can be between 1 and the default value of 14,400 seconds. After a message has been accepted by a carrier, however, we cannot guarantee that the message will not be queued after this period. We recommend that this value be at least 5 seconds.",
          "disabled": true
        }
      ]
    },
    "url": {
      "raw": "{{2010-04-01-Accounts-AccountSid-Messages.json-Url}}/2010-04-01/Accounts/:AccountSid/Messages.json",
      "host": [
        "{{2010-04-01-Accounts-AccountSid-Messages.json-Url}}"
      ],
      "path": [
        "2010-04-01",
        "Accounts",
        ":AccountSid",
        "Messages.json"
      ],
      "variable": [
        {
          "key": "AccountSid",
          "value": "{{TWILIO_ACCOUNT_SID}}",
          "description": "(Required) The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will create the resource."
        }
      ]
    },
    "description": "Send a message from the account used to make the request with the phone number you purchased from Twilio in the previous step or with any other Twilio phone number you have associated in your account.\n\nRead more about it in the [Twilio Docs](https://www.twilio.com/docs/sms/api/message-resource#create-a-message-resource)"
  },
  "response": [
    {
      "name": "Created",
      "originalRequest": {
        "method": "POST",
        "header": [
          {
            "description": "Added as a part of security scheme: basic",
            "key": "Authorization",
            "value": "Basic <credentials>"
          }
        ],
        "body": {
          "mode": "urlencoded",
          "urlencoded": [
            {
              "key": "To",
              "value": "<string>",
              "description": "The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format for SMS/MMS or [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses) for other 3rd-party channels."
            },
            {
              "key": "AddressRetention",
              "value": "<string>",
              "description": "Determines if the address can be stored or obfuscated based on privacy settings (This can only be one of retain)"
            },
            {
              "key": "ApplicationSid",
              "value": "<string>",
              "description": "The SID of the application that should receive message status. We POST a `message_sid` parameter and a `message_status` parameter with a value of `sent` or `failed` to the [application](https://www.twilio.com/docs/usage/api/applications)'s `message_status_callback`. If a `status_callback` parameter is also passed, it will be ignored and the application's `message_status_callback` parameter will be used."
            },
            {
              "key": "Attempt",
              "value": "<integer>",
              "description": "Total number of attempts made ( including this ) to send out the message regardless of the provider used"
            },
            {
              "key": "Body",
              "value": "<string>",
              "description": "The text of the message you want to send. Can be up to 1,600 characters in length."
            },
            {
              "key": "ContentRetention",
              "value": "<string>",
              "description": "Determines if the message content can be stored or redacted based on privacy settings (This can only be one of retain)"
            },
            {
              "key": "ForceDelivery",
              "value": "<boolean>",
              "description": "Reserved"
            },
            {
              "key": "From",
              "value": "<string>",
              "description": "A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, an [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses) that is enabled for the type of message you want to send. Phone numbers or [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from Twilio also work here. You cannot, for example, spoof messages from a private cell phone number. If you are using `messaging_service_sid`, this parameter must be empty."
            },
            {
              "key": "MaxPrice",
              "value": "<number>",
              "description": "The maximum total price in US dollars that you will pay for the message to be delivered. Can be a decimal value that has up to 4 decimal places. All messages are queued for delivery and the message cost is checked before the message is sent. If the cost exceeds `max_price`, the message will fail and a status of `Failed` is sent to the status callback. If `MaxPrice` is not set, the message cost is not checked."
            },
            {
              "key": "MediaUrl",
              "value": "[\"<uri>\",\"<uri>\"]",
              "description": "The URL of the media to send with the message. The media can be of type `gif`, `png`, and `jpeg` and will be formatted correctly on the recipient's device. The media size limit is 5MB for supported file types (JPEG, PNG, GIF) and 500KB for [other types](https://www.twilio.com/docs/sms/accepted-mime-types) of accepted media. To send more than one image in the message body, provide multiple `media_url` parameters in the POST request. You can include up to 10 `media_url` parameters per message. You can send images in an SMS message in only the US and Canada."
            },
            {
              "key": "MessagingServiceSid",
              "value": "<string>",
              "description": "The SID of the [Messaging Service](https://www.twilio.com/docs/sms/services#send-a-message-with-copilot) you want to associate with the Message. Set this parameter to use the [Messaging Service Settings and Copilot Features](https://www.twilio.com/console/sms/services) you have configured and leave the `from` parameter empty. When only this parameter is set, Twilio will use your enabled Copilot Features to select the `from` phone number for delivery."
            },
            {
              "key": "PersistentAction",
              "value": "[\"<string>\",\"<string>\"]",
              "description": "Rich actions for Channels Messages."
            },
            {
              "key": "ProvideFeedback",
              "value": "<boolean>",
              "description": "Whether to confirm delivery of the message. Set this value to `true` if you are sending messages that have a trackable user action and you intend to confirm delivery of the message using the [Message Feedback API](https://www.twilio.com/docs/sms/api/message-feedback-resource). This parameter is `false` by default."
            },
            {
              "key": "SmartEncoded",
              "value": "<boolean>",
              "description": "Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`."
            },
            {
              "key": "StatusCallback",
              "value": "<uri>",
              "description": "The URL we should call using the `status_callback_method` to send status information to your application. If specified, we POST these message status changes to the URL: `queued`, `failed`, `sent`, `delivered`, or `undelivered`. Twilio will POST its [standard request parameters](https://www.twilio.com/docs/sms/twiml#request-parameters) as well as some additional parameters including `MessageSid`, `MessageStatus`, and `ErrorCode`. If you include this parameter with the `messaging_service_sid`, we use this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/sms/services/api). URLs must contain a valid hostname and underscores are not allowed."
            },
            {
              "key": "ValidityPeriod",
              "value": "<integer>",
              "description": "How long in seconds the message can remain in our outgoing message queue. After this period elapses, the message fails and we call your status callback. Can be between 1 and the default value of 14,400 seconds. After a message has been accepted by a carrier, however, we cannot guarantee that the message will not be queued after this period. We recommend that this value be at least 5 seconds."
            }
          ]
        },
        "url": {
          "raw": "{{2010-04-01-Accounts-AccountSid-Messages.json-Url}}/2010-04-01/Accounts/:AccountSid/Messages.json",
          "host": [
            "{{2010-04-01-Accounts-AccountSid-Messages.json-Url}}"
          ],
          "path": [
            "2010-04-01",
            "Accounts",
            ":AccountSid",
            "Messages.json"
          ],
          "variable": [
            {
              "key": "AccountSid"
            }
          ]
        }
      },
      "status": "Created",
      "code": 201,
      "_postman_previewlanguage": "json",
      "header": [
        {
          "key": "Content-Type",
          "value": "application/json"
        }
      ],
      "cookie": [
      ],
      "body": "{\n \"account_sid\": \"ACF8\",\n \"api_version\": \"exercitation eiusmod amet laboris\",\n \"body\": \"consectetur exercitation officia magna\",\n \"date_created\": \"consectetur exercitation proident\",\n \"date_sent\": \"culpa sint labore\",\n \"date_updated\": \"proident\",\n \"direction\": \"outbound-call\",\n \"error_code\": -64742646,\n \"error_message\": \"nostrud sint Ut\",\n \"from\": \"Excepteur cillum aute\",\n \"messaging_service_sid\": \"MGDB\",\n \"num_media\": \"dolor veniam non\",\n \"num_segments\": \"et ut sint ut amet\",\n \"price\": \"Lorem reprehenderit\",\n \"price_unit\": \"Excepteur tempor i\",\n \"sid\": \"MM79\",\n \"status\": \"received\",\n \"subresource_uris\": {},\n \"to\": \"Ut non id\",\n \"uri\": \"magna sit esse\"\n}"
    }
  ]
}