Getting email body using vba code

时间:2015-07-28 17:14:41

标签: vba email outlook

I am trying to get the email header and body inside my email in outlook using VBA. I am using the Application_NewMail() event handler to process that new mail has arrived, but I cannot figure out how to get the header and body from there.

This is the code that I have inside the Application_NewMail() event handler:

Private WithEvents myOlItems  As Outlook.Items

Private Sub Application_NewMail()
Dim olApp As Outlook.Application
Dim oNS         As NameSpace
Dim oFolder     As MAPIFolder
Dim oNewMail    As MailItem
Set olApp = Outlook.Application
Set oNS = GetNamespace("MAPI")
Set oFolder = oNS.GetDefaultFolder(olFolderInbox)
Set oNewMail = oFolder.Items.GetFirst
'This is the string that hold the mail body.
Dim mailBody As String
Dim mailArg() As String


    MsgBox "New Mail!"

End Sub

This function is firing properly once I receive emails. I successfully get the messagebox to pop up. But I want to be able to read the mail body and header to insert into a database.

The actual database side of it I know how to do, but I am unsure how to get the header and body from the email. I have tried something like this:

Set olItem = ActiveExplorer.Selection.Item(1)
    mailBody = oNewMail.Body
    mailArg = Split(mailBody, vbLf)

    'Check to see what is inside the body. We need to say Tank X: Y
    MsgBox "This is line one " & mailArg(0) & "This is line two " & mailArg(1)

And I receive the error: Object variable or With block variable not set

Any help will be greatly appreciated.

1 个答案:

答案 0 :(得分:1)

您需要处理Application类的NewMailEx事件。对于Microsoft Outlook处理的每个接收项,此事件将触发一次。该项可以是几种不同项类型之一,例如,MailItem,MeetingItem或SharingItem。 EntryIDsCollection字符串包含与该项对应的条目ID。

当新邮件到达收件箱时以及客户端规则处理发生之前,将触发NewMailEx事件。您可以使用EntryIDCollection数组中返回的条目ID来调用NameSpace.GetItemFromID方法并处理该项。

Outlook对象模型提供了三种使用项主体的主要方法:

  1. Body
  2. HTMLBody
  3. Word编辑器。 Inspector类的WordEditor属性返回表示邮件正文的Word文档实例。因此,您可以使用Word对象模型对邮件正文执行任何操作。
  4. 最后,您可以使用PropertyAccessor对象(请参阅MailItem类的相应属性)来读取“PR_TRANSPORT_MESSAGE_HEADERS”属性值。

      propertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E")