Wednesday, August 17, 2016

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API which requires using OAuth authentication to get an Access Token.

The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library https://github.com/bblanchon/ArduinoJson which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater.

To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You need to authorize it in you tenant (eg build a small app that can do that which will prompt for authorization). One that is done you then need to set that ClientId variable in the sketch

String ClientId = "8fe353d6-efa0-4b0f-aafb-ab7cf3a9b307";

I've put a copy of this Sketch up https://github.com/gscales/Arduino-MRK1000/blob/master/REST-Office365SendSample.ino the code looks like


#include <ArduinoJson.h>

#include <Base64.h>
#include <ArduinoHttpClient.h>

/*
This example creates a client object that connects and transfers
data using always SSL.

It is compatible with the methods normally related to plain
connections, like client.connect(host, port).

Written by Arturo Guadalupi
last revision November 2015

*/

#include <SPI.h>
#include <WiFi101.h>

char ssid[] = "SSOecure"; //  your network SSID (name)
char pass[] = "pass@#";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)
const size_t MAX_CONTENT_SIZE = 5120;

//Office365 Credentials
String ExUserName = "user@domain.com";
String ExPassword = "passw";
String ClientId = "8fe353d6-efa0-4b0f-aafb-ab7cf3a9b307";
//Message Details
String Auth = ExUserName + ":" + ExPassword;
String Subject = "Subject of the Message";
String To = "mailbox@domain.com";
String Body = "Something happening in the Body";
String Access_Token = "";

bool DebugResponse = false;

int cCount = 0;

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiSSLClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
  TokenAuth(ClientId,ExUserName,ExPassword);
  if(Access_Token.length() > 0){
      Serial.println("Send Message");
      SendRest(Access_Token,To,Subject,Body);
      Serial.println("Done");
  }

}

void TokenAuth(String ClientId,String UserName, String Password)
{
     char endOfHeaders[] = "\r\n\r\n";
     char passwordCA[Password.length()+1];
     Password.toCharArray(passwordCA,Password.length()+1);
     String content = "resource=https%3A%2F%2Foutlook.office.com&client_id=" + ClientId + "&grant_type=password&username=" + ExUserName + "&password=" + URLEncode(passwordCA) + "&scope=openid";
     Serial.println("\nStarting connection to server...");
     if (client.connectSSL("login.windows.net", 443)) {
       Serial.println("connected to server");
       client.print("POST ");
       client.println("https://login.windows.net/Common/oauth2/token HTTP/1.1");
       client.println("Content-Type: application/x-www-form-urlencoded");
       client.println("client-request-id: " + ClientId);
       client.println("return-client-request-id: true");
       client.println("x-client-CPU: x32");
       client.println("x-client-OS: Arduino");
       client.println("Host: login.windows.net");
       client.print("Content-Length: ");
       client.println(content.length());
       client.println("Expect: 100-continue");
       client.println(""); 
       client.println(content);
       client.find(endOfHeaders);
       bool ok =  client.find(endOfHeaders);
       if (!ok) {
         Serial.println("No response or invalid response!");
       }
       else{
         Serial.println("Request Okay");
       }
       char response[MAX_CONTENT_SIZE];
       readAuthReponse(response, sizeof(response));
    }
}

void readAuthReponse(char* content, size_t maxSize) {
  size_t length = client.readBytes(content, maxSize);
  content[length] = 0;
  Serial.println(content);
  content[length] = 0;
  DynamicJsonBuffer jsonBuffer;
  JsonObject&root = jsonBuffer.parseObject(content);
  if (!root.success()) {
    Serial.println("JSON parsing failed!");
  }
  else{
      String token = root["access_token"]; 
      Access_Token = token;
  }
  
}


String URLEncode(const char* msg)
{
    const char *hex = "0123456789abcdef";
    String encodedMsg = "";

    while (*msg!='\0'){
        if( ('a' <= *msg && *msg <= 'z')
                || ('A' <= *msg && *msg <= 'Z')
                || ('0' <= *msg && *msg <= '9') ) {
            encodedMsg += *msg;
        } else {
            encodedMsg += '%';
            encodedMsg += hex[*msg >> 4];
            encodedMsg += hex[*msg & 15];
        }
        msg++;
    }
    return encodedMsg;
}


void SendRest(String Bearer,String MessageTo, String MessageSubject, String MessageBody)
{
    //DebugResponse = true;
    char endOfHeaders[] = "\r\n\r\n";  
    String content = "{";
    content += "        \"Message\": {";  
    content += "           \"Subject\": \"" + MessageSubject + "\",";  
    content += "            \"Body\": {";  
    content += "                \"ContentType\": \"Text\",";  
    content += "                \"Content\": \"" + MessageBody + "\"";  
    content += "                       },";  
    content += "            \"ToRecipients\": [";  
    content += "                {";  
    content += "                    \"EmailAddress\": {";  
    content += "                        \"Address\": \"" + MessageTo + "\"";  
    content += "                    }";  
    content += "                }";  
    content += "            ]";  
    content += "        },";  
    content += "        \"SaveToSentItems\": \"false\"";  
    content += "    }";  
    Serial.println("\nStarting connection to server...");
    // if you get a connection, report back via serial:
    if (client.connectSSL("outlook.office365.com", 443)) {
      Serial.println("connected to server");
      client.print("POST ");
      client.print("https://outlook.office365.com/api/v2.0/me/sendmail");
      client.println(" HTTP/1.1"); 
      client.print("Host: "); 
      client.println("outlook.office365.com");
      client.print("Authorization: Bearer ");
      client.println(Bearer); 
      client.println("Connection: close");
      client.print("Content-Type: ");
      client.println("application/json");
      client.println("User-Agent: mrk1000Sender");
      client.print("Content-Length: ");
      client.println(content.length());
      client.println();
      client.println(content);
      char okayString[] = "HTTP/1.1 202 Accepted";
      bool ok =  client.find(okayString);
      if (!ok) {
        Serial.println("Message Sent");
      }
      else{
        Serial.println("Request Failed");
      }
    }

}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if(DebugResponse){
  while (client.available()) {
    char c = client.read();
    Serial.print(c); 
  }
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();
    // do nothing forevermore:
    while (true);
  }
}


void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}


Wednesday, August 10, 2016

Sending a Message via EWS from an Arduino MKR1000

The Internet of Things is all the rage these days and one of the most popular prototyping platform for any electronic projects these days is the Arduino. The new MKR1000 Arduino board combines the functionality from the Zero board with a WifiSheild on a compact board and pretty cheap $35. It looks like




These boards are pretty cool and take you back in some ways to 80's with some of the programming challenges that come with memory restriction devices. Eg the MRK1000 has 32Kb of SRAM which is half that of Commodore 64 although it runs at 48Mhz vs the 1.33 Mhz the Commodore could manage (I know this isn't a fair technical comparison just trying provide a bit of contrast).

The nice thing with this board also is because it implements a cryptoauthentication chip it can do SSL communication which can be problem with low power boards because of the amount of processing power required for SSL. So at the bare bones this board can run code and logic that will allow HTTPS communication.

The following is a simple how to for sending an email from an Exchange Mailbox using EWS in Office365 from one of these devices using the following two libraries

https://github.com/arduino-libraries/ArduinoHttpClient  (used for the HTTPS communication)

https://github.com/agdl/Base64 (used to create the Base64 Authentication header)

Preparation

Before you can use the board to talk to Office365 you need to load the SSL certificates required for SSL communication. This may sound a little weird to most people as this process you would never have to worry about with most coding you would do. However because of the limited power/size of this unit it can only hold 10 certificates for WebSites you want to talk to and it has no ability to load them dynamically so you first need to copy the cert to the device. To do this you need to use the following sketch https://github.com/arduino-libraries/WiFi101-FirmwareUpdater and then use the upload certificates to Wifi in the Wifi101 firmware update which is in the Arduino IDE https://www.arduino.cc/en/Main/Software (eg just add the root certificate for outlook.office365.com see below)


To use the example sketch I've created you need to install the following Libraries in the Arduino IDE

https://github.com/arduino-libraries/ArduinoHttpClient  (used for the HTTPS communication)

https://github.com/agdl/Base64 (used to create the Base64 Authentication header)

Once you do that you ready to use the following Sketch the code is relativity simple, with EWS on Office365 it supports Basic and Oauth authentication as this is just for prototyping I've gone with basic auth which means you just need a Base64 library to do the encoding of the authentication header.

The code use the Wifi Sketch as a base which allows you to specify the SSID and password to use for your wifi in the following two variables

char ssid[] = "ssid"; // your network SSID (name)
char pass[] = "password";

then when you upload the sketch and connect to the serial port on the MRK1000 it will try to connect to the WIFI and then run the SendMessageEWS function.

I have the following variables in the sketch to hold the Office365 username and password and data for the message Subject, Body and To Recipients

//Office365 Credentials
String ExUserName = "user@domaiin.onmicrosoft.com";
String ExPassword = "passwprd";

//Message Details
String Auth = ExUserName + ":" + ExPassword;
String Subject = "Subject of the Message";
String To = "user@domain.com";
String Body = "Something happening in the Body";


The SendMessageEWS function first creates a variable that contains the EWS SOAP Message to send. (At this point you need to be careful of how big this string could get). The rest of the code makes a connection to the Office365 Service using the Arduino http client library that makes use of that Crypo chip for SSL. It then starts sending the headers necessary for the EWS POST and submits the POST String as the payload. I don't have anything written to parse the response but the raw output is witten back to the serial port so you can see if it was successfully or if something went wrong. I've put a copy of the Sketch here on GitHub https://github.com/gscales/Arduino-MRK1000/blob/master/EWS-Office365SendSample.ino the code looks like

#include <Base64.h>
#include <ArduinoHttpClient.h>

/*
This example creates a connection to Office365 and Send an Email
via SOAP

Uses code from the following examples

https://www.arduino.cc/en/Tutorial/WiFiWebClient


*/

#include <SPI.h>
#include <WiFi101.h>

char ssid[] = "ssid"; //  your network SSID (name)
char pass[] = "password";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

//Office365 Credentials
String ExUserName = "user@domaiin.onmicrosoft.com";
String ExPassword = "passwprd";

//Message Details
String Auth = ExUserName + ":" + ExPassword;
String Subject = "Subject of the Message";
String To = "user@domain.com";
String Body = "Something happening in the Body";



int cCount = 0;

int status = WL_IDLE_STATUS;
WiFiSSLClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
  SendMessageEWS(Auth,To,Subject,Body);

}


void SendMessageEWS(String AuthString,String MessageTo, String MessageSubject, String MessageBody)
{
    //Auth Header
    char basicHeader[AuthString.length()+1];
    AuthString.toCharArray(basicHeader,AuthString.length()+1);
    int inputStringLength = sizeof(basicHeader); 
    int encodedLength = Base64.encodedLength(inputStringLength); 
    char encodedString[encodedLength]; 
    Base64.encode(encodedString, basicHeader, inputStringLength); 
    String AuthHeader = "Basic ";

    //EWS SOAP Request
    String content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    content += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    content += "<soap:Header>";
    content += "<t:RequestServerVersion Version=\"Exchange2013_SP1\" />";
    content += "</soap:Header>";
    content += "<soap:Body>";
    content += "<m:CreateItem MessageDisposition=\"SendAndSaveCopy\">";
    content += "<m:SavedItemFolderId>";
    content += "<t:DistinguishedFolderId Id=\"sentitems\" />";
    content += "</m:SavedItemFolderId>";
    content += "<m:Items>";
    content += "<t:Message>";
    content += "<t:Subject>" + MessageSubject + "</t:Subject>";
    content += "<t:Body BodyType=\"HTML\">" + MessageBody + "</t:Body>";
    content += "<t:ToRecipients>";
    content += "<t:Mailbox>";
    content += "<t:EmailAddress>" + MessageTo + "</t:EmailAddress>";
    content += "</t:Mailbox>";
    content += "</t:ToRecipients>";
    content += "</t:Message>";
    content += "</m:Items>";
    content += "</m:CreateItem>";
    content += "</soap:Body>";
    content += "</soap:Envelope>";

    
    Serial.println("\nStarting connection to server...");
    // if you get a connection, report back via serial:
    if (client.connectSSL("outlook.office365.com", 443)) {
      Serial.println("connected to server");
      client.print("POST ");
      client.print("https://outlook.office365.com/EWS/Exchange.asmx");
      client.println(" HTTP/1.1"); 
      client.print("Host: "); 
      client.println("outlook.office365.com");
      client.print("Authorization: Basic ");
      client.println(encodedString); 
      client.println("Connection: close");
      client.print("Content-Type: ");
      client.println("text/xml");
      client.println("User-Agent: mrk1000Sender");
      client.print("Content-Length: ");
      client.println(content.length());
      client.println();
      client.println(content);      
    }
  
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.print(c); 
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();
    // do nothing forevermore:
    while (true);
  }
}


void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}