Delete a mailitem permanently in outlook

Machinegon picture Machinegon · Aug 7, 2013 · Viewed 11.4k times · Source

I'm trying to delete a mailitem using the outlook API. Like the following,

Dim objMail
For each objMail in objFolder.Items
objMail.Delete
Next

Obviously, deleting an item straight away is to simple. Outlook just move it into the "Deleted Items" folder instead of deleting it. I tried to get the "Deleted Items" folder using

OutlookNameSpace.GetDefaultFolder(olDeletedItems)

and delete the mail again, but the PST the code is working on is not the default mailbox and the folder returned is the wrong deleted items folder. How can I permanently delete this mailitem?

I tried to loop through all folders in the current store, but there's no way of telling which folder is the deleted items folder except by comparing names, I can't do that since the programs will be used in multiple languages and the name is different for each version.

PS: I cannot use a third party dll :(

Help!

Answer

Kazimierz Jawor picture Kazimierz Jawor · Aug 7, 2013

First problem of your code is not appropriate loop you use. If you want to delete (almost anything in VBA) you need to loop your collection from the last element to first. If not, you change the order of the collection- after you delete 1st element >> 2nd one is moved to 1st position and will not be deleted.

Therefore this code should delete all items from your DeltetedItems folder:

Sub Delete_all_from_dust_bin()

    Dim myFolder As Outlook.Folder

    Set myFolder = Application.GetNamespace("MAPI"). _
            GetDefaultFolder(olFolderDeletedItems)

    Dim i As Long
    For i = myFolder.items.Count To 1 Step -1

        myFolder.items(i).Delete

    Next i

End Sub

Obviously, you could prepare similar code for deleting from any other folder. You will run both deletion loops to remove items for sure.

Some additional remarks for MailItem.Delete Method from MSDN:

The Delete mothod deletes a single item in a collection. To delete all items in the Items collection of a folder, you must delete each item starting with the last item in the folder. For example, in the items collection of a folder, AllItems, if there are n number of items in the folder, start deleting the item at AllItems.Item(n), decrementing the index each time until you delete AllItems.Item(1).

Edit due to some comments from OP.

Even if you need to delete some items (not all) remember to use the loop type I presented above. If you need to refer to any other DeletedItems folder in other stores you can find this folder in these ways:

'with index reference
Application.GetNamespace("MAPI").Stores(2).getdefaultfolder(olFolderDeletedItems)
'with name reference
Application.GetNamespace("MAPI").Stores("Business Mail").getdefaultfolder(olFolderDeletedItems)

I don't know if this works with all Outlook versions but it's working with Outlook 2010.