It can be very useful to run a VBA macro when new mail is received in Outlook. A customer asked me to write something that would log an entry to a SQL database when an email produced contact form was received.

It’s easy to do but can take a bit of trial and error to get working just how you want it.

You need to add an event listener to the Inbox which will process incoming messages. A the following code to ThisOutlookSession:

  1. Option Explicit
  2. Private WithEvents inboxItems As Outlook.Items
  3. Private Sub Application_Startup()
  4. Dim outlookApp As Outlook.Application
  5. Dim objectNS As Outlook.NameSpace
  6. Set outlookApp = Outlook.Application
  7. Set objectNS = outlookApp.GetNamespace("MAPI")
  8. Set inboxItems = objectNS.GetDefaultFolder(olFolderInbox).Items
  9. End Sub
  10. Private Sub inboxItems_ItemAdd(ByVal Item As Object)
  11. On Error GoTo ErrorHandler
  12. Dim Msg As Outlook.MailItem
  13. Dim MessageInfo
  14. Dim Result
  15. If TypeName(Item) = "MailItem" Then
  16. MessageInfo = "" & _
  17. "Sender : " & Item.SenderEmailAddress & vbCrLf & _
  18. "Sent : " & Item.SentOn & vbCrLf & _
  19. "Received : " & Item.ReceivedTime & vbCrLf & _
  20. "Subject : " & Item.Subject & vbCrLf & _
  21. "Size : " & Item.Size & vbCrLf & _
  22. "Message Body : " & vbCrLf & Item.Body
  23. Result = MsgBox(MessageInfo, vbOKOnly, "New Message Received")
  24. End If
  25. ExitNewItem:
  26. Exit Sub
  27. ErrorHandler:
  28. MsgBox Err.Number & " - " & Err.Description
  29. Resume ExitNewItem
  30. End Sub

Screenshot showing the location of where to paste code into ThisOutlookSession to trigger a macro when new mail is received.

You need to restart Outlook for the code to become active.

The above code will produce a simple message box that shows some of the message properties:

Screenshot of VBA Macro being triggered when new mail is received in Outlook

You can of course do whatever you like with the message when it is received. I used it to insert rows into a SQL table, then move the message to a different folder. It works very well.

It’s worth taking a look at all of the available properties of the Outlook mailitem that are available.

If you found this post helpful, I’d really appreciate it if you would rate it 😀

Let me know in the comments section if you have any questions.

posted on 2019-09-27 15:14  懒懒的呐喊  阅读(329)  评论(0编辑  收藏  举报