Skip to main content

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

Popular posts from this blog

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Gr...

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 ...

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why ...
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.