11

I have the following code which tells when new message has arrived!

Private Sub Application_NewMail()
    MsgBox "New Mail Has Arrived"
End Sub

How do I read the body,subject of this mail? Are there any good tutorials for outlook programming?

I found msdn tutorial which was useful but was general overview.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
kinkajou
  • 3,664
  • 25
  • 75
  • 128

1 Answers1

20

You'll need something like this:

Private WithEvents myOlItems  As Outlook.Items

Private Sub Application_Startup()
    Dim olApp As Outlook.Application
    Dim objNS As Outlook.NameSpace
      Set olApp = Outlook.Application
      Set objNS = olApp.GetNamespace("MAPI")
      Set myOlItems = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub myOlItems_ItemAdd(ByVal item As Object)

On Error GoTo ErrorHandler

  Dim Msg As Outlook.MailItem

  If TypeName(item) = "MailItem" Then
    Set Msg = item

    MsgBox Msg.Subject
    MsgBox Msg.Body

  End If

ProgramExit:
  Exit Sub
ErrorHandler:
  MsgBox Err.Number & " - " & Err.Description
  Resume ProgramExit
End Sub

Paste the code into ThisOutlookSession and restart Outlook. When a message enters your default local Inbox you'll see the popup with subject and body.

kinkajou
  • 3,664
  • 25
  • 75
  • 128
JimmyPena
  • 8,694
  • 6
  • 43
  • 64