How to send SMS from Microsoft Excel using Twilio Programmable Messaging

March 08, 2022
Written by
Reviewed by

How to send SMS from Microsoft Excel using Twilio Programmable Messaging

Using Twilio, you can programmatically send customized SMS the way you want to, but your users may just want to send out SMS from a simple spreadsheet of their customers, without having to worry about how to program. Luckily, you can add that functionality to an Excel spreadsheet for them with Microsoft Office Scripts.

In this post, you will learn how to build a tool to send SMS to your customers from a Microsoft Excel sheet using Microsoft Office Scripts.

An Excel spreadsheet containing phone numbers and SMS messages. The Delivery Attempt Status column starts of empty. When the bulk SMS tool runs, status column is filled out row by row with the result of sending SMS.

Are you using Google Sheets instead of Excel? Learn how to send SMS notifications from Google Sheets with Twilio.

Prerequisites

To build this solution, you will need:

  • A free Twilio account
  • An active phone number in your account if you want to send messages from a specific number, otherwise, you can get started without any setup for alphanumeric sender IDs.
  • Access to Microsoft Office Scripts (as described here) which includes:
    • Excel on the web (other platforms, such as desktop, are not supported).
    • OneDrive for Business.
    • Any commercial or educational Microsoft 365 license with access to the Microsoft 365 Office desktop apps, such as:
      • Office 365 Business
      • Office 365 Business Premium
      • Office 365 ProPlus
      • Office 365 ProPlus for Devices
      • Office 365 Enterprise E3
      • Office 365 Enterprise E5
      • Office 365 A3
      • Office 365 A5
  • Basic Node.js and Typescript knowledge

Twilio account setup

If you don’t already have a Twilio account, you can quickly get a free account here.

Then, go and buy a new phone number from Twilio. The cost of the phone number will be applied to your free promotional credit, if you're on a trial account.

Instead of using a Twilio Phone Number, you can also use an Alphanumeric Sender ID if your country supports it and you have a paid account. Learn more about Alphanumeric Sender ID and how to set it up here.

Once you’ve set up your account and phone number, enable Twilio to send SMS to the countries you want. Details on permissions settings for international SMS can be found here.

If you are using a trial Twilio account, you can only send text messages to Verified Caller IDs. Verify the phone numbers you want to SMS if it isn't on the list of Verified Caller IDs.

That's it, but to develop with Twilio you'll need to take note of a couple of things. Navigate to your Twilio account page and take note of your Twilio Account SID, Auth Token, and your Twilio Phone Number located at the bottom left of the page.

Account Info box holding 3 read-only fields: Account SID field, Auth Token field, and Twilio phone number field.

Creating the Excel Online spreadsheet

Head to Excel Online and create a new blank Workbook:

The Excel Online start page with a button "New blank workbook"

Create 4 column headers in the new workbook you just created:

  • To: The number of the recipient you are sending a message to. Make sure you put this into E.164 Format, otherwise you will receive an error.
  • Message: The content of the message you want to send to the recipient.
  • From: The number you are sending the message from. This could either be a Twilio provisioned number. As mentioned in the setup, you can also use an alphanumeric sender ID as long as the country of the recipient number supports alphanumeric sender IDs.
  • Delivery Attempt Status: This column will be automatically filled in with information around the delivery attempt.

4 column headers in an Excel Online spreadsheet: To, Message, From, and Delivery Attempt Status

Next, head to the Automate tab (This tab is only available if your account has office scripts enabled. If you have it enabled in your account and still do not see this tab, it might be because Office Script can take up to 48 hours to be enabled according to the documentation)

Excel ribbon with the Automate tab selected and pointed out by an arrow.

Click on the create new script button.

In the Automate tab of Excel, the New Script button is highlighted by an arrow.

This will open a code editor on the right-hand side. Add the following code into the script editor:

const TWILIO_ACCOUNT_SID = "<YOUR_ACCOUNT_SID>";
const TWILIO_AUTH_TOKEN = "<YOUR_ACCOUNT_AUTH_TOKEN>";

const main = async (workbook: ExcelScript.Workbook) => {
  try {
    // send single SMS function
    const sendSMS = async (to: string, body: string, from: string) => {
      try {
        var myHeaders = new Headers();
        myHeaders.append("Authorization", `Basic ${btoa(`${TWILIO_ACCOUNT_SID}:${TWILIO_AUTH_TOKEN}`)}`);
        var formdata = new FormData();
        formdata.append("To", to);
        formdata.append("Body", body);
        formdata.append("From", from);


        var requestOptions = {
          method: 'POST',
          headers: myHeaders,
          body: formdata,
        };

        const response = await fetch(`https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Messages.json`, requestOptions)

        var responseJSON: object = await response.json()

        if (response.status === 201) {
          return {
            message: `✅ SMS attempt has been sent to Carrier (MessageID: ${responseJSON['sid']})`
          }
        } else {
          throw Error(`❌ SMS send attempt failed (error ${responseJSON['code']}: ${responseJSON['message']})`)
        }
      } catch (e) {
        return e
      }
    }

    // loop through all cells and send
    let selectedSheet = workbook.getActiveWorksheet();
    const rowCount = selectedSheet.getRange().getRowCount();

    for (let currentRow = 1; currentRow < rowCount; currentRow++) {
      if (selectedSheet.getCell(currentRow, 0).getValue() === '') {
        break;
      }
      const toNumber = selectedSheet.getCell(currentRow, 0).getValue() as string
      const body = selectedSheet.getCell(currentRow, 1).getValue() as string
      const fromNumber = selectedSheet.getCell(currentRow, 2).getValue() as string

      const response: string = await sendSMS(
        toNumber,
        body,
        fromNumber
      );
      selectedSheet.getCell(currentRow, 3).setValue(response['message'])
    }
  } catch (e) {
    console.log(e)
  }
}

Replace <YOUR_ACCOUNT_SID> with your Twilio Account SID  and  <YOUR_ACCOUNT_AUTH_TOKEN> with the Auth Token you took note of earlier.

At this point, your Twilio account credentials will be visible to anyone who has access to this script. Make sure that you do not openly share the script with anyone you wouldn’t trust your account credentials with as this could be used to access your Twilio account outside the script. To keep this simple, you are using the Account SID and Auth Token for authentication in this tutorial, however it would be better to implement this using API Keys.

Finally, press the Save Script button to save this script:

The Office Script Code Editor panel with the "Save script" button highlighted

To make sure this works, add some data into your sheet and press the Run button:

The Office Script Code Editor panel with the "Run" button highlighted

Your script will run through each row and try to send an SMS. Depending on if the delivery attempt was successful or not, you will see the info in the Delivery Attempt Status column.

The spreadsheet after the SMS script has run. The Delivery Attempt Status column contains multiple success messages and one failure because the phone number is invalid.

If you want to run this script with an embedded button, you can do so as explained in this Microsoft Office blog:

The user clicked on the script overflow menu. The menu shows multiple items including an item to "Add button". The "Add button" item is highlighted.

You can customize the look of the button and place it where you want. If you press the button, the same script will be triggered to send the outbound SMS.

The spreadsheet contains a button saying "Send Mass SMS"

Future Improvements

This is a great starting point, but you can improve this solution in many ways:

  • Office Scripts does not allow you to store any authentication tokens on the user's machine, which is why you had to hard-code the Twilio Auth Token. Anyone who can read the Office Script can also read the Auth Token which is a security risk. There are a couple of solutions to this:
    • You can build a similar solution as a web service and call the web service from Office Scripts. You can then use network security to only make the web service available to your users. Alternatively, you can add authentication to your web service, but Office Script won't let you store security tokens, so users will need to authenticate every time the service is called.
    • You can build the same functionality using a Power Automate flow. Power Automate flow has connectors for Excel to work with spreadsheets and for Twilio to send SMS. The connections between  Excel, Twilio, and Power Automate will be stored in the Power Platform.
  • Instead of using a specific number, you could use a Messaging Service. This is a free-of-charge service that optimizes the number selection process for you. You could adjust the script to not show the From column and use a Messaging Service ID as the sender within the script itself.
  • You could integrate WhatsApp as an additional Channel, both as a specific sender or integrated into the previously mentioned Messaging Service. More information can be found here.

Sending text messages from Microsoft Excel Online with Twilio

Using Office Scripts, you can add functionality to your Excel sheets using Node.js and TypeScript. You can use this functionality to grab the data from the spreadsheet, and send text messages using Twilio by making HTTP requests to Twilio's APIs. By combining Microsoft Office Scripts and Twilio's APIs, you developed a bulk SMS tool to send text messages using Excel.

It’s important to note that this tutorial focuses on building a solution quickly to send bulk SMS without much development effort, not necessarily on scalability and robustness. If you plan to build a long-term solution that is scalable and robust, we would recommend looking into building out a similar solution as suggested in the future improvements sections.

You used a single Twilio Phone Number in this tutorial, which works well if you're not sending a very large number of text messages. However, if you need to send a large amount of bulk SMS, you'll need to update your solution to handle the increased scale. To do this, you can follow this guide to sending bulk SMS with Twilio and Node.js,  or by reaching out to our sales team and having a detailed discussion about your use case to find the ideal solution for your business.

Author:

Ted Gieschen is a Munich based senior solutions engineer in the DACH region who is passionate about helping customers find elegant technical solutions to their business problems. When Ted isn’t busy finding solutions for his customer’s problems he’s most likely out running 🏃🏻‍♂️, climbing 🧗🏻‍♂️ or snowboarding 🏂. Feel free to reach out to him at tgieschen [at] twilio.com

Reviewer:

Pradheep Rajendirane is a senior Solutions Engineer based in Paris passionate about coding and more specifically building web applications. Check out his GitHub profile here.