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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8005713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:08:44  来源:igfitidea点击:

Using VBA to read new Outlook Email?

vbaoutlookoutlook-vba

提问by kinkajou

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?

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

I found msdntutorial which was useful but was general overview.

我发现msdn教程很有用,但只是一般概述。

回答by JimmyPena

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.

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