Skip to main content

Scripting Exchange Web Services (2007) with VBS and Powershell

I’ve been playing around with the new Exchange 2007 Web Services and thought I would share a few scripts. With a lot of API’s being deemphasized or disappearing completely in Exchange 2007, Exchange Web Services are the brave new world that confronts people who want to develop applications that run against an Exchange 2007 server. Like any other WebService EWS allows you to invoke different methods which will perform specific tasks by sending SOAP messages that contain certain properties and then receiving specifically formatted responses. For a scripting point of view it’s pretty easy firstly you need to authenticate the default authentication is NTLM so there is no need to worry about FBA synthetic logons and then it’s just a matter of posting a XML formatted SOAP message. If your familiar with using WebDAV the underlying methods you use are the same but the requests and responses are very different. Lets start with a simple send email example.

smSoapMessage = "<?xml version='1.0' encoding='utf-8'?>" _
& "<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" " _
& " xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">" _
& "<soap:Body><CreateItem MessageDisposition=""SendAndSaveCopy"" " _
& " xmlns=""http://schemas.microsoft.com/exchange/services/2006/messages""> " _
& "<SavedItemFolderId><DistinguishedFolderId Id=""sentitems""
xmlns=""http://schemas.microsoft.com/exchange/services/2006/types""/>" _
& "</SavedItemFolderId><Items><Message
xmlns=""http://schemas.microsoft.com/exchange/services/2006/types"">" _
& "<ItemClass>IPM.Note</ItemClass><Subject>" & stSubjet & "</Subject><Body
BodyType=""Text"">" & ebEmailBody & "</Body><ToRecipients>" _
& "<Mailbox><EmailAddress>" & EmailAddress &
"</EmailAddress></Mailbox></ToRecipients></Message></Items>" _
& "</CreateItem></soap:Body></soap:Envelope>"
set req = createobject("microsoft.xmlhttp")


The first thing you need to do is build a SOAP message for scripting I prefer to just to build the message manually as a string. You could use the XMLDOM object but this requires a lot more lines of code and complexity. This soap message is a CreateItem request that creates a message and saves it in the SentItems folder. The MessageDisposition Attribute controls how the Exchange server goes about handling this message after its received in this instance it is sent and also a copy is saved to the folder listed in the DistinguishedFolderId element.


set req = createobject("microsoft.xmlhttp")
req.Open "post", "http://" & servername & "/ews/Exchange.asmx", False,"domain\user", "password"
req.setRequestHeader "Content-Type", "text/xml"
req.setRequestHeader "translate", "F"
req.send smSoapMessage
wscript.echo req.status
wscript.echo
wscript.echo req.responsetext

The IIS virtual directory you use to access the Exchange Webservice is http://Servername/EWS. If your send is successful you will see a Status of 200 returned if not you usually get a 50x error message. The response messages are usually pretty good for diagnosing what your doing wrong (its generally a formatting issue with the soap message).

Another method of interest is the GetFolder method which is roughly equivalent to a propfind in WebDAV in that it allows you to retrieve properties from a folder. Some properties of interest might be things like the foldersize or the unread message count on the inbox. The following is a SOAP request that can be used to get the unread message count on the inbox. (Switching from VBS to Powershell this time)

$smSoapMessage = "<?xml version='1.0' encoding='utf-8'?>" `
+ "<soap:Envelope xmlns:soap=`"http://schemas.xmlsoap.org/soap/envelope/`" " `
+ " xmlns:xsi=`"http://www.w3.org/2001/XMLSchema-instance`" xmlns:xsd=`"http://www.w3.org/2001/XMLSchema`"" `
+ " xmlns:t=`"http://schemas.microsoft.com/exchange/services/2006/types`" >" `
+ "<soap:Body>" `
+ "<GetFolder xmlns=`"http://schemas.microsoft.com/exchange/services/2006/messages`"
" `
+ " xmlns:t=`"http://schemas.microsoft.com/exchange/services/2006/types`"> " `
+ "<FolderShape> " `
+ "<t:BaseShape>Default</t:BaseShape> " `
+ "</FolderShape> " `
+ "<FolderIds> " `
+ "<t:DistinguishedFolderId Id=`"inbox`"/> " `
+ "</FolderIds> " `
+ "</GetFolder> " `
+ "</soap:Body></soap:Envelope>"


The BaseShape element controls which properties are returned by the query the default set generally contains all the properties you need to do basic tasks (including the unread count). But if you want to get all the properties or include additional properties there are other elements to do this job.

$servername = "ws03r2eeexchlcs"
$strRootURI = "http://" + $servername + "/ews/Exchange.asmx"
$WDRequest = [System.Net.WebRequest]::Create($strRootURI)
$WDRequest.ContentType = "text/xml"
$WDRequest.Headers.Add("Translate", "F")
$WDRequest.Method = "Post"
$WDRequest.Credentials = $cdUsrCredentials
$bytes = [System.Text.Encoding]::UTF8.GetBytes($smSoapMessage)
$WDRequest.ContentLength = $bytes.Length
$RequestStream = $WDRequest.GetRequestStream()
$RequestStream.Write($bytes, 0, $bytes.Length)
$RequestStream.Close()
$WDResponse = $WDRequest.GetResponse()
$ResponseStream = $WDResponse.GetResponseStream()
$ResponseXmlDoc = new-object System.Xml.XmlDocument
$ResponseXmlDoc.Load($ResponseStream)
$UreadNameNodes = @($ResponseXmlDoc.GetElementsByTagName("t:UnreadCount"))
"Number of Unread Email : " + $UreadNameNodes[0].'#text'

The one important thing here when you are looking at the results returned by the EWS and your using getElementsByTagName method in Powershell is make sure you use the @ array specifier In front of the method call or you wont be able to index into the collection and access the elements. Authentication in Powershell can be handled in two ways if you want to specify which credentials to use you can use a credential object with a line such as

$cdUsrCredentials = new-object System.Net.NetworkCredential("Administrator", "Evaluation1", "CONTOSO")

And then set the request object to use those credentials

$WDRequest.Credentials = $cdUsrCredentials

Or you can specify to use the credentials from the user context that is invoking the script by setting the request object like

$WDRequest.UseDefaultCredentials = $True

The Last thing to look at is the restriction element this allows you to specify which items you want to return. So if you where to use the FindItem method to list items in your inbox and you wanted to just return those items that where unread and only 24 hours old then you could use something like this in the restriction section of the SOAP message.


+ "<Restriction>" `
+ "<t:And>" `
+ "<t:IsEqualTo>" `
+ "<t:FieldURI FieldURI=`"message:IsRead`"/>"`
+ "<t:FieldURIOrConstant>" `
+ "<t:Constant Value=`"0`"/>" `
+ "</t:FieldURIOrConstant>" `
+ "</t:IsEqualTo>" `
+ "<t:IsGreaterThanOrEqualTo>" `
+ "<t:FieldURI FieldURI=`"item:DateTimeSent`"/>"`
+ "<t:FieldURIOrConstant>" `
+ "<t:Constant Value=`"" + $datetimetoquery.ToUniversalTime().AddDays(-1).ToString("yyyy-MM-ddThh:mm:ssZ")
+ "`"/>"`
+ "</t:FieldURIOrConstant>"`
+ "</t:IsGreaterThanOrEqualTo>"`
+ "</t:And>"`
+ "</Restriction>"`


Like Exchange 200x when you query the Exchange store with a Datetime range that datetime range should be converted to the ISO dateformat and also because Exchange stores date and times in UTC you should convert the date and time you want to query for into UTC before you use it (and also convert the returned times back into Local time so they make sense). Powershell lets you tap into the .NET time conversion functions which makes things a lot simpler then they where in VBS.

I’ve created 4 scripts all up both in VBS and Powershell the scripts do the following tasks

Sendews : Sends a message using EWS
Ureadews : Reads the UnreadCount property of the inbox
Shureadews : Shows the Time,From,Subject and size of all unread messages in the inbox
Shureadewstday Shows the Time,From,Subject and size of all unread messages in the inbox just for the past 24 hours

I’ve put a downloadable copy of the script here.

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 Graph is limited to a m

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 ap

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 I wrote th
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.