Skip navigation

Using a Script to Delete All Messages in a Set of Mailboxes

Downloads
49238.zip

I need to create a script that I can use to connect to several mailboxes and delete all messages within them. I could manually connect to them, of course. But I have 10 accounts that aren't associated with users but are being used by other services running on our network, and I need to clean all of them up periodically. What would such a script look like?

This type of cleanup activity calls for the use of the Collaboration Data Objects (CDO) 1.21 programming library, an optional component in Outlook that supports dynamic logons. As long as you know the server name and mailbox alias and have appropriate permissions, you can write CDO code to log on to a specific mailbox and perform operations on it. It doesn't matter whether Outlook is running or not.

The code in Web Listing 1 consists of three procedures:

  • PurgeMailbox—the main procedure your script will call
  • ProcessCDOFolder—a recursive procedure that processes all items and subfolders in a given folder
  • DeleteCDOFolderItems—the procedure that actually deletes the items from the folder

Put all three procedures in your script, then use one or more statements to call PurgeMailbox with specific server and mailbox alias names:

Call PurgeMailbox("myserver", _ 
  "mymailbox") 

The PurgeMailbox procedure uses those parameters, separated by a line feed, to build a profile information string that the Session.Logon method can use to log on to that specific mailbox, as the code at callout A in Web Listing 1 shows.

The ProcessCDOFolder procedure is a recursive procedure because it calls itself. Recursion enables the code to handle any number of folders, not just the Inbox and other folders on the same level.

Both the PurgeMailbox and Process-CDOFolder procedures skip contacts folders so that the code can run unattended—from the Windows scheduler, for example. One quirk of Outlook security is that touching a contacts folder with CDO code puts up a security prompt, even if you don't access properties of any individual items.

To download the code for Web Listing 1 click the 49238.zip hotlink. As with any code that acts on a mailbox—especially code that deletes items—you should test, test, and test again before implementing this code in a production environment.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish