Working with Email from Powershell via Exchange Web Services

I came across one of those situations the other day where we were considering purchasing a product purely for one simple function, extracting attachments from an email and saving it to a folder.. It’s kind of like the time I brought the fanciest food process because I was too lazy to grate cheese (first world problems I know). Sure it did a great job grating cheese, but it was an absolute bugger to clean! But hey, it looks good, so worth it right….

Anyway, like my Cheese Grater analogy, the issue with buying a fancy piece of software is the cost and maintenance are overkill for a simple task. So I rolled up my sleeves and went about attacking this the powershell way. A couple of late nights neglecting my screaming kids I put together a script to do exactly what we wanted. So here is the masterpiece!

The first thing you want to do is install the Microsoft Exchange Web Services Managed API 2.2 . This will give you a library to enable all the fancy pants libraries to interface directly with your Exchange Server (or Office 365) leveraging Exchange Web Services (EWS). You only need to refer to the DLL in your script to take advantage of the all the exchange EWS goodness.

First up you will need to import the DLL as follows:

Import-Module -Name “C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll”

After this, you can start using all of the EWS objects and get down and dirty with your Exchange environment!

Next, create an ExchangeService Object, and set some variables specific to your Exchange enviornment.

Right, now that we’ve setup our environment, let’s grab an email! In the below email I’ve searched my inbox for any email containing ‘stapler’ in the subject. Then, I save any attachments found to a local folder on my computer.

Voila, thats it! Now if I look in c:\temp I can see all of the email attachments saved there.

Milton - Office Space

To make all this a bit more reusable, I’ve created a Powershell module to simplify things. Simply import the PSM1 file (the EWS DLL needs to be available) then you can perform functions similar to below:

EmailManagement.psm1 (8 Kb)

Enjoy, I’m off to eat something greasy, why do I feel like cheese all of a sudden..

Leave a Reply

Your email address will not be published. Required fields are marked *