Using events in Outlook
Event trapping in Outlook is easy for the Application object, since it has its own class module (ThisOutlookSession). Many other objects in Outlook can react to events, but have no class modules. That's only reasonable, since those objects are temporary by their nature - like MailItem or Items objects. To handle events for those kinds of objects, you need to create your own class modules.
Here is an example of basic event handling for Outlook objects, to illustrate the principles. The code starts with the Init() procedure, which sets up event trapping for the Items object in your inbox. It reacts to the ItemAdd event, which is triggered any time a new item gets added to the inbox. This is what you would use to filter incoming mail, for example. The code then sets up event trapping for that new item as well, in this case for the Open event of the item. (To keep it simple, I have only made it react to MailItems.) To turn off event handling again, run the Cleanup() procedure.
This code doesn't really do anything useful in itself; it just notifies you any time With very little work, you could turn this piece of code into a custom inbox filtering tool, to augment the Rules Wizard. You could, for example, check all incoming mail for attachments. Or to take it one step further, you could use the Rules Wizard to move all items from a specific sender into a separate folder, and then use event handling to automatically save all attachments from those items.
You could use item-level event trapping to, for example, move all items after you've read them. Or use it to block the user from saving attachments or forwarding e-mail etc.
Public WithEvents itms As Items Public ItemsCollection As Collection Sub Init() 'set up event handling Set itms = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items Set ItemsCollection = New Collection End Sub Sub Cleanup() 'run this To turn event handling off again Set itms = Nothing Set ItemsCollection = Nothing End Sub Private Sub itms_ItemAdd(ByVal Item As Object) Dim clsEventCatcher As EventCatcher If TypeOf Item Is MailItem Then MsgBox "I notice a new item: " & Item.Subject 'set up an Object To catch events For this mail item Set clsEventCatcher = New EventCatcher Set clsEventCatcher.itm = Item 'put the Object In a collection so it doesn't vanish when the Sub finishes running ItemsCollection.Add clsEventCatcher End If End Sub 'in a class module that I called EventCatcher: Public WithEvents itm As MailItem Private Sub itm_Open(Cancel As Boolean) MsgBox "Hey, you opened the item!" End Sub