Skip to main content

Deleting Items in a mailbox using Exchange Web Services and Powershell

This post continues on from my post a couple of weeks ago on digesting the quarantine mailbox in Exchange 2007. If you are digesting the quarantine mailbox one thing you might also want to automate is the purging of quarantined messages from the mailbox after a month if nothing has been done with them. Also if you have unmonitored mailboxes for auto-responses etc you might also want something that will delete messages that are older than a certain time period so to do this with EWS you need to look at first building a list of the itemIDs for the items you want to delete using a FindItem request and then batching your delete request for these items. For performance reasons its best to make sure that your batches that delete the items are a reasonable size to avoid performance issues on your CAS server.

The DeleteItem request in EWS is relatively straight forward to use but there are a few options you should be aware of. When you delete an item within the Exchange Store there are a couple of different types of deletes you can do. A Soft delete puts the item being deleted into the dumpster of the folder you’re deleting it from where its stays until the deleted item retention period expires. A Hard Delete removes the item completely meaning there’s is no hope of recovery. Then there is the normal Outlook/OWA client functionality which moves an item into the deleted items folder where its sits until a user empties their deleted items folder where its then put into the dumpster of the deleted items folder where its stays until the deleted item retention period expires. EWS caters for all these modes of operation via the EWS.DisposalType see http://msdn.microsoft.com/en-us/library/exchangewebservices.disposaltype(EXCHG.80).aspx

The other things to be aware of is if your deleting calendar items is you can control if calendar responses are sent to the meeting organizers and you can also control how recurring task deletes are handled. Because I’m focusing on Mail items I’ll leave these to the side.

So an EWS deleteitem request that would delete an array of itemid you pass into it and return a string that showed the results would look something like this

public String DeleteItems(BaseItemIdType[] idItemstoDelete,DisposalType diType) {

String rtReturnString = "";

DeleteItemType diDeleteItemRequest = new DeleteItemType();

diDeleteItemRequest.ItemIds = idItemstoDelete;

diDeleteItemRequest.DeleteType = diType;

diDeleteItemRequest.SendMeetingCancellationsSpecified = true;

diDeleteItemRequest.SendMeetingCancellations = CalendarItemCreateOrDeleteOperationType.SendToNone;

DeleteItemResponseType diResponse = esb.DeleteItem(diDeleteItemRequest);

ResponseMessageType[] diResponseMessages = diResponse.ResponseMessages.Items;

int DeleteSuccess = 0;

int DeleteError = 0;

foreach (ResponseMessageType repMessage in diResponseMessages)

{

if (repMessage.ResponseClass == ResponseClassType.Success) {

DeleteSuccess++;

}

else {

DeleteError++;

Console.WriteLine("Error Occured");

Console.WriteLine(repMessage.MessageText.ToString());

}

}

rtReturnString = DeleteSuccess.ToString() + " Messages Deleted " + DeleteError + " Errors";

return rtReturnString;

}

What I’ve done is included this method into my Powershell EWS library so I can then use it with a couple of lines of script. To actually find the items to delete we need to use another existing method in the library that will return a generic list of items within a particular mailbox folder based on the items messsage class and a DateRange. So this allows us to write a script like the folloiwng to do a Soft Delete of any items within a mailbox where those Items where received during the duration that is specified (startdate is the earliist received time enddate is the datetime of the newest received item to delete). If you want to filter based on a particualar message class this can be achieve by modifying the following line eg a modification such as this would mean only NDR's would be deleted.

$msgList = $ewc.FindItems($fldarry, $drDuration, $null, "REPORT.IPM.Note.NDR")

To use this script you need my ewsutil library which you can download from http://msgdev.mvps.org/exdevblog/ewsutil.zip

The script to do the delete looks like this a few thing to take note of is the date range of the items that will be deleted

$drDuration = new-object EWSUtil.EWS.Duration
$drDuration.StartTime = [DateTime]::UtcNow.AddDays(-365)
$drDuration.EndTime = [DateTime]::UtcNow.AddDays(-31)

And the type of delete its going to peform which is a soft delete.

$ewc.deleteItems($itarry,[EWSUtil.EWS.DisposalType]::SoftDelete

The script seperates the deletes into batchs of 100 for performance reasons.

The script use my EWCConnection object which I’ve documented here it allows both impersonation and delegation authentication models.

With any script like this that performs deletes you should take that atmost of great care to ensure you have backups before running and that you have fully tested the process.

I’ve put a download of this script here the script itself looks like

[void][Reflection.Assembly]::LoadFile("C:\EWSUtil.dll")

$mbMailboxEmail = "quantinemailbox@domain.com"
$ewc = new-object EWSUtil.EWSConnection($mbMailboxEmail,$false, $null,$null,$null,$null)


$drDuration = new-object EWSUtil.EWS.Duration
$drDuration.StartTime = [DateTime]::UtcNow.AddDays(-365)
$drDuration.EndTime = [DateTime]::UtcNow.AddDays(-31)

$dTypeFld = new-object EWSUtil.EWS.DistinguishedFolderIdType
$dTypeFld.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::inbox

$mbMailbox = new-object EWSUtil.EWS.EmailAddressType
$mbMailbox.EmailAddress = $mbMailboxEmail
$dTypeFld.Mailbox = $mbMailbox


$fldarry = new-object EWSUtil.EWS.BaseFolderIdType[] 1
$fldarry[0] = $dTypeFld
$msgList = $ewc.FindItems($fldarry, $drDuration, $null, "")
$batchsize = 100
$bcount = 0
if ($msgList.Count -ne 0){
$itarry = new-object EWSUtil.EWS.ItemIdType[] $batchsize
for($ic=0;$ic -lt $msgList.Count;$ic++){
if ($bcount -ne $batchsize){
$itarry[$bcount] = $msgList[$ic].ItemId
$bcount++
}
else{
$ewc.deleteItems($itarry,[EWSUtil.EWS.DisposalType]::SoftDelete)
$itarry = $null
$itarry = new-object EWSUtil.EWS.ItemIdType[] $batchsize
$bcount = 0
$itarry[$bcount] = $msgList[$ic].ItemId
$bcount++
}

}
$ewc.deleteItems($itarry,[EWSUtil.EWS.DisposalType]::SoftDelete)
}

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.