Skip to main content

Twitter a Exchange Calendar using Powershell and EWS - Exchange 2007

Micro-Blogging is one of the Web 2.0 technologies that has been getting a bit of run of late its one of the tools a seemingly new breed of politicians are using to garner support and awareness of their movements. But its also used by a growing number of everyday people and businesses as a method of pervaying certain messages and other sometimes seemly useless pieces of information. Maybe one of the keys to twitter's success is it fills the gap between availibilty and straight calendaring. I think the scope of what could be done with twitter when you start to intergrate this into traditional communication technology should see this technology expand even more (well as long as we get some creative people pushing the limits).

Exchange mostly provides the same type of information in different formats so using the Twitter API and the Exchange API's you can start to combine the functionality of both systems to start providing different new funcationality. Eg in this sample Im using a script to query an Exchange calendar and then take the text from the current appointment (if there is one) trim it to 140 characters and then post this as a Twitter update. There's logic in the script to first check the current twitter status so the script can be run at intervals and ensure that multiple updates wont be sent for multiple appointments. If you have more then one appointment scheduled at the same time it will just use the first.

So what could you use it for ?.. well any compay,club or small group who has a calendar or events can create twitter feed for these event by simply placeing the events in a Exchange calendar and then let the script read and twitter the status updates. Most of our lives are scripted by our calendar anyway so here a way to save on typing.

How does it work.

There are already a few good Powershell twitter scripts so i grabbed some code out of Mike Ormonds's Sample and started working in some other code. The first thing the scirpt does is goes and grabs the current twitter status. It then goes and queries the mailbox calendar to see if there are any appointments that are in the current time frame. If it find one it then posts the subject of the appointment as a twitter status update. To do the Exchange side I've use Exchange Web Services via some code i've packed into my EWSUtil powershell library (actually im reusing the stuff from the RSS feed script).

Making it work

To make this work you first need a twitter account and a Exchange 2007 Mailbox you need to put your twitter username and password in the following varibles

$twitterusername = "username"
$twitterpassword = "password"

Then put the Email address of the mailbox with the calendar you want to pull the data from and the Exchange Username and password to access this mailbox (or you can use EWS impersonation if you wanted to agregate several mailboxes) in the following varibles.

$emEmailAddress = "twittest@domain.com"
$userName = "twittest"
$password = "Password"
$domain = "domain"

In the

$ExchangeServername = "servername"

put the CAS Servername

If your using a cloud mailbox on Microsoftonline set the domain to blank and use something like (I've built this using a BPOS mailbox)

$emEmailAddress = "twittest@youdomain.microsoftonline.com"
$userName = "twittest@youdomain.microsoftonline.com"
$password = "youpassword"
$domain = ""

To use this you need the EWSUtil library I've put a download of this script here the script itself looks like (note this script is pretty alpha issh so do your own testing first)

$twitterusername = "username"
$twitterpassword = "password"
$ExchangeServername = "servername"
$emEmailAddress = "twittest@domain.com"
$userName = "twittest"
$password = "Password"
$domain = "domain"

function updateTwiterStatus($PostString){

$tweetstring = [String]::Format("status={0}", $PostString )
[System.Net.ServicePointManager]::Expect100Continue = $false
$request = [System.Net.WebRequest]::Create("http://twitter.com/statuses/update.xml")
$request.Credentials = new-object System.Net.NetworkCredential($twitterusername,$twitterpassword)
$request.Method = "POST"
$request.ContentType = "application/x-www-form-urlencoded"
$formdata = [System.Text.Encoding]::UTF8.GetBytes($tweetstring)
$request.ContentLength = $formdata.Length
$requestStream = $request.GetRequestStream()
$requestStream.Write($formdata, 0, $formdata.Length)
$requestStream.Close()
$response = $request.GetResponse()
$reader = new-object System.IO.StreamReader($response.GetResponseStream())
$returnvalue = $reader.ReadToEnd()
$reader.Close()

}

function GetTwitterStatus(){
[System.Net.ServicePointManager]::Expect100Continue = $false
$request = [System.Net.WebRequest]::Create("http://twitter.com/users/show/" + $twitterusername)
$request.Credentials = new-object System.Net.NetworkCredential($twitterusername,$twitterpassword)
$request.Method = "GET"
$request.ContentType = "application/x-www-form-urlencoded"
$response = $request.GetResponse()
$ResponseStream = $response.GetResponseStream()
$ResponseXmlDoc = new-object System.Xml.XmlDocument
$ResponseXmlDoc.Load($ResponseStream)
$StatusNodes = @($ResponseXmlDoc.getElementsByTagName("status"))
$returnStatus = $StatusNodes[0].text
$ResponseXmlDoc.Save("c:\dd.xml")
return $returnStatus.ToString()
}


$casURL = "https://" + $ExchangeServername + "/EWS/Exchange.asmx"
[void][Reflection.Assembly]::LoadFile("C:\temp\EWSUtil.dll")
$ewc = new-object EWSUtil.EWSConnection($emEmailAddress,$false, $userName, $password,$domain, $casURL)
$drDuration = new-object EWSUtil.EWS.Duration
$drDuration.StartTime = [DateTime]::UtcNow
$drDuration.EndTime = [DateTime]::UtcNow.AddMinutes(15)
$upset = 0
[EWSUtil.EWS.DistinguishedFolderIdType] $dType = new-object EWSUtil.EWS.DistinguishedFolderIdType
$dType.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::calendar
$qfolder = new-object EWSUtil.QueryFolder($ewc,$dType, $drDuration,$false,$true)
foreach ($item in $qfolder.fiFolderItems){
if ($item.Location -ne $null){
$twitString = $item.Subject.ToString() + " " + $item.Location.ToString()
}
else{
$twitString = $item.Subject.ToString()
}
if ($twitString.Length -gt 140){$twitString = $twitString.Substring(0,139)}
[String]$currentStatus = GetTwitterStatus
$twitString = $twitString.Substring(0,$twitString.length-1)
write-host $twitString.ToLower().ToString()
write-host $currentStatus.ToLower().ToString()
if ($currentStatus.ToLower().ToString() -ne $twitString.ToLower().ToString()){
if ($statusup -ne 3){$statusup = 1}
$upset = 1
}
else{
$statusup = 3
}
}
if ($statusup -eq 1){
updateTwiterStatus($twitString)
"Twitter Status Updated"
}
else {"Nothing changed since last update"}

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.