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");
}