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

EWS-FAI Module for browsing and updating Exchange Folder Associated Items from PowerShell

Folder Associated Items are hidden Items in Exchange Mailbox folders that are commonly used to hold configuration settings for various Mailbox Clients and services that use Mailboxes. Some common examples of FAI's are Categories,OWA Signatures and WorkHours there is some more detailed documentation in the https://msdn.microsoft.com/en-us/library/cc463899(v=exchg.80).aspx protocol document. In EWS these configuration items can be accessed via the UserConfiguration operation https://msdn.microsoft.com/en-us/library/office/dd899439(v=exchg.150).aspx which will give you access to either the RoamingDictionary, XMLStream or BinaryStream data properties that holds the configuration depending on what type of FAI data is being stored. I've written a number of scripts over the years that target particular FAI's (eg this one that reads the workhours  http://gsexdev.blogspot.com.au/2015/11/finding-timezone-being-used-in-mailbox.html is a good example ) but I didn't have a gene...

Sending a MimeMessage via the Microsoft Graph using the Graph SDK, MimeKit and MSAL

One of the new features added to the Microsoft Graph recently was the ability to create and send Mime Messages (you have been able to get Message as Mime for a while). This is useful in a number of different scenarios especially when trying to create a Message with inline Images which has historically been hard to do with both the Graph and EWS (if you don't use MIME). It also opens up using SMIME for encryption and a more easy migration path for sending using SMTP in some apps. MimeKit is a great open source library for parsing and creating MIME messages so it offers a really easy solution for tackling this issue. The current documentation on Send message via MIME lacks any real sample so I've put together a quick console app that use MSAL, MIME kit and the Graph SDK to send a Message via MIME. As the current Graph SDK also doesn't support sending via MIME either there is a workaround for this in the future my guess is this will be supported.
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.