使用VBA阅读新的Outlook电子邮件?

时间:2011-11-04 06:39:43

标签: vba outlook outlook-vba

我有以下代码,告诉新邮件何时到达!

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

我如何阅读这封邮件的主体?有没有关于outlook编程的好教程?

我找到了msdn教程,该教程很有用,但总体概述。

1 个答案:

答案 0 :(得分:18)

你需要这样的东西:

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

将代码粘贴到ThisOutlookSession并重新启动Outlook。当邮件进入您的默认本地收件箱时,您将看到包含主题和正文的弹出窗口。