您的位置:首页 > 编程语言 > VB

How to run a VBA macro when new mail is received in Outlook

2020-02-02 05:51 2691 查看

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

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:

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.

转载于:https://www.cnblogs.com/jjj250/p/11598144.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
didui8202 发布了0 篇原创文章 · 获赞 0 · 访问量 687 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐