Office is a platform that many people and enterprises, use every day.  Building on that platform gives developers immediate access to millions of potential customers.  In recent years Microsoft has made great strides to unify the programming model between their online products and their Windows based tools.  This post will show you how to leverage the Office Add-in features to build on Outlook and Outlook.com add-in that can send an SMS message to any US based phone number found in an email item.

Step 1 – Create Your Project in Napa

While you can build an Office add-in in Visual Studio, Microsoft has developed a very nice online tool for building them called Napa.  You can access this tool at http://www.napacloudapp.com.  You’ll need to sign in with your Microsoft account and then you’ll be asked what type of add-in you want to created.

CreateAddIn

Select Mail Add-in for Office and give it a name.  If you don’t already have an Office developer account you can click the link on this page to request one.  Click Create button and then you’ll be taken to the Napa project screen.

Step 2 – Configure Project Settings

Click on the wrench icon wrenchon the left tool bar and you’ll see the project settings screen.  On the General tab you can enter your add-in settings.  As we want this add-in to be relatively unobtrusive, lets set the height to 32px.

ProjectStart

Mail Add-ins can be triggered in both Read and Compose mode.  For this add-in we’ll just be working with the Read Form.  Click on the Read Form tab and you’ll see the settings shown below.

Properties

Your add-in is basically a web page that will be embedded into an iframe within Outlook.com and the Outlook client.  The Start page can be any page accessible to the application even on another server, but you can also host the page locally which is how the default project is defined.  The settings page also allows you to specify a different page to render when running on tablets and phones.  For our purposes, we’ll stick to just using the Home.html page.

Mail add-ins can be triggered when a mail item is in read mode or if certain criteria are met within the mail item.  In the screen shot you can see that there is an option for detecting the presence of known entities.  These entities include:

  • Meeting Suggestion – any reference to meetings such as “Let’s meet for lunch tomorrow”
  • Task Suggestion – action based sentences such as “Edit this spreadsheet”
  • Address – a US formatted address over one or more lines
  • URL – any web address with or without protocol specifications such as “www.microsoft.com” or “https://manage.azure.com”
  • Phone Number – a US formatted telephone number
  • Email Address – any SMTP email address
  • Contact – a reference to a person’s contact information such as a combination of name and other personal details in close proximity

For our add-in we only want to trigger when Outlook recognizes a phone number known entity and so we’ll select that option.  Make the changes and click on the Apply button.

Step 3 – Edit HTML/CSS/JavaScript

The next step is to modify the boilerplate HTML and CSS in Home.html and Home.css.  Click on the Files icon Files in the left tool bar to switch back to the files view.  Click on the Home.html file under the AppRead/Home directory and replace the contents with the markup below.

[code language=”html”]

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>InstantSMS</title>
    https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js

    <link href="../../Content/Office.css" rel="stylesheet" type="text/css" />
    https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js

    <link href="../App.css" rel="stylesheet" type="text/css" />
    http://../App.js

    <!– Add reference to jQuery.Base64 –>
    http://jquery.base64.js

    <!– Add reference to Font Awesome –>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

    <link href="Home.css" rel="stylesheet" type="text/css" />
    http://Home.js
</head>
<body>
    <!– Page content –>
   

<

div id=”content-main”>
       

           
           
           
       

       

<

div id=”statusDisplay” class=”hide”>
           

            <span class="sms-status" id="status"></span>
        </div>
</body>
</html>

[/code]

This markup contains the links to several of the JavaScript libraries we’ll need.  These include a jQuery plugin for Base64 encoding that you can download here.  I’m also using the FontAwesome library.  The controls on this page are basically a form for sending the SMS and another <DIV> for displaying status messages.

The following is the CSS settings I’m using but feel free to modify as you like.

[code language=”css”]

/* Page-specific styling */
.sms-button {
height:32px;
margin: 0;
}

.sms-text {
height:32px;
width:50%;
}

.sms-select {
height:32px;
}

.sms-status {
font-weight: bold;
font-size: 12px;
}

.sms-status-success {
color: green;
}

.sms-status-error {
color: red;
}

.sms-close {
cursor: pointer;
display:inline;
}

.hide { display: none; }
.show { display: inline; }

[/code]

In the Home.js file you’ll find some boilerplate JavaScript. Leave the Office.initialize method but change the displayItemDetails function to displayInstantSMS. The code below shows the displayInstantSMS method.

[code language=”javascript”]
function displayInstantSMS() {
//Get the list of phone numbers entities found in the mail item
var item = Office.cast.item.toItemRead(Office.context.mailbox.item);
var entities = item.getEntities();
var phoneNums = entities.phoneNumbers;

//Load them into the HTML
var i = 0;
for (i = 0; i < phoneNums.length; i++) {
$(‘#phoneNums’).append($(‘<option>’, {
value: phoneFormat(phoneNums[i].phoneString),
text: phoneFormat(phoneNums[i].phoneString)
}));
}

//Wire up the click event for the SMS Button
$(‘#btnSMS’).click(function() {
var msg = $(‘#msgText’).val();
SendSMS($(‘#phoneNums’).val(), msg);
});

//Wire up the click event for the Status Close Button
$(‘#iconClose’).click(function() {
SwapDisplay($(‘#statusDisplay’),$(‘#smsFields’));
});
}
[/code]

In this method we cast a variable to a Mailbox item in Read mode so that we can access the known entities and from that we are able to get the phone numbers found in the mail item.  An interesting point is that when the add-in is used in Office365 running in the browser, the add-in is activated by clicking on the found phone number in which case the list will only have one item in it.  In the Outlook app, it will contain the list of all phone numbers found.  I’m using a phone number formatting function to standardize the format of the phone numbers in the dropdown.

Next we wire up the click events to the button for sending the SMS and to the close icon on the status display.

Step 4 – Hooking up the HTML to Twilio

If you’re not familiar with Twilio, they offer a suite of services for communications including making voice calls, sending SMS, and video and audio conferencing.  They offer easy to use REST based APIs and we’ll be using their SMS messaging API for our add-in.  You’ll need to sign up for an account on their site but they offer free trial accounts that can be used to send SMS messages to phone numbers that are validated on their site.  If you opt for a paid account, that restriction is lifted.

The API to send a SMS message is quite simple as this curl example shows.

curl -X POST ‘https://api.twilio.com/2010-04-01/Accounts/[AccountSID]/Messages.json’
–data-urlencode ‘To=7025551212’
–data-urlencode ‘From=+17024443535’
–data-urlencode ‘Body=This is a message’
-u [AccountSID]:[AuthToken]

AccountSID is your Twilio username and AuthToken is the equivalent of a password.  The From phone number is the Twilio phone number that you create on the Twilio site  The rest is pretty much self explanatory.

[code language=”javascript”]
// Use Twilio to send SMS Message
function SendSMS(recipient, messageText) {
var accountSID = ‘[AccountSID]’;
var authToken = ‘[AuthToken]’;
var fromNumber = ‘+17024443535’;
var AuthorizationToken = $.base64.btoa(accountSID + ‘:’ + authToken);
var body = ‘From=’ + encodeURIComponent(fromNumber) + ‘&To=’ + encodeURIComponent(recipient) + ‘&Body=’ + encodeURIComponent(messageText);
var twilioUrl = ‘https://api.twilio.com/2010-04-01/Accounts/’ + accountSID + ‘/SMS/Messages.json’
$.ajax({
url: twilioUrl,
type: ‘POST’,
data: body,
contentType: ‘application/x-www-form-urlencoded’,
beforeSend: function(xhr) {
xhr.setRequestHeader(‘Authorization’, ‘Basic ‘ + AuthorizationToken);
},
error: function(error) {
var data = $.parseJSON(error.responseText);
$(‘#status’).text(data.message);
$(‘#status’).addClass(‘sms-status-error’);
SwapDisplay($(‘#smsFields’), $(‘#statusDisplay’));
},
success: function(data) {
$(‘#status’).text(data.status);
$(‘#status’).addClass(‘sms-status-success’);
SwapDisplay($(‘#smsFields’), $(‘#statusDisplay’));
}
});
}
[/code]

The SendSMS function formats the URL for the Twilio REST request and passes in the To, From, and Body fields as form fields in the HTTP POST.  Note that the AccountSID and AuthToken are combined and then Base64 encoded using the jQuery plugin as per standard HTTP Basic Authorization.  If the message is sent successfully then we update and show the status message, and if not we display the error message returned in the status.  The SwapDisplay method is just used to change which of the modes is displayed in the add-in.

Note – Because the JavaScript is executed in the browser, it’s not a good idea to put your AuthToken inside the client code as any client could see it.  This secret could be secured via Azure Key Vault or by creating an online service that calls Twilio but was beyond the scope of this article.  If you’d like to get more details on how to write a more secure solution, contact us at consulting@wintellect.com to learn more.

Step 5 – The End Result

 

From Napa you can click on the Run icon run to load the add-in into your Office365 mailbox.  Click on an email which contains a phone number and you’ll see it has a dashed hyperlink.  Click on it and your add-in will load.

Here is what the add-in looks like in Office365 running in a browser.

Outlook.com1

And this is what it looks like in Outlook 2016 Preview

Outlook1

For more information on Office development with Napa, visit the Napa Getting Started page.  You can also download the complete project here: InstantSMS