PDA

View Full Version : Open Email Message



Stephanie
06-01-2006, 08:21 AM
I would like to run some code whenever an email is double-clicked and opened. How do start this?

mvidas
06-02-2006, 07:12 AM
Hi Stephanie,

This is definately possible, though a little tricky in setting it up initially.

Go to your outlook vba editor (Alt-F11 from outlook). Expand the ThisOutlookSession, and paste in the following:

Option Explicit
Dim myMailItemTrapper As MailEventClass
Private Sub Application_Startup()
Set myMailItemTrapper = New MailEventClass
End Sub
Private Sub Application_Quit()
Set myMailItemTrapper = Nothing
End SubNow, go to Insert, then Class Module. Single-click on the new class module in the project window, and press F4 to open the properties for it. Change the (Name) of the class module to "MailEventClass". Now, in the code pane for the class module, paste in the following:'Taken and modified from:
'http://blogs.officezealot.com/legault/articles/2224.aspx
Option Explicit
Dim WithEvents objInspectors As Outlook.Inspectors
Dim WithEvents objOpenInspector As Outlook.Inspector
Dim WithEvents objMailItem As Outlook.MailItem
Private Sub Class_Initialize()
Set objInspectors = Application.Inspectors
End Sub
Private Sub Class_Terminate()
Set objOpenInspector = Nothing
Set objInspectors = Nothing
Set objMailItem = Nothing
End Sub
Private Sub objInspectors_NewInspector(ByVal Inspector As Inspector)
If Inspector.CurrentItem.Class = olMail Then
Set objMailItem = Inspector.CurrentItem
Set objOpenInspector = Inspector
End If
End Sub
Private Sub objMailItem_Open(Cancel As Boolean)
MsgBox "objMailItem_open has been triggered"
End Sub

Private Sub objMailItem_Read()
MsgBox "objMailItem_Read has been triggered"
End Sub
To start this, either just restart outlook, or press F5 in ThisOutlookSession when the cursor is in the application_startup event to manually run that.
Any time you double-click a message, you'll see two message boxes telling you when the events are run (depending on when you want the code to be fired).
When you make changes to the code, you'll have to re-run the application_startup event or restart outlook.

Let us know if you have any questions!
Matt

Stephanie
06-02-2006, 09:46 AM
That is awesome. Thank you so much for your help.