如何找到电子邮件中单词的位置并仅获取电子邮件的一部分?

How to find positions of words in email and get just part of email?

我正在尝试查找电子邮件正文中某些单词的位置(您好、您好、早上好、亲切的问候)并获取电子邮件的一部分。对于 70% 的收到电子邮件,它工作正常,但对于某些电子邮件,它无法识别这些词。如果我手动将电子邮件转发给我,然后进行搜索,它会找到它们,但如果我通过宏将其转发给我,问题仍然存在。

Sub Display()
    Dim oApp As Outlook.Application
    Dim objFolder As Outlook.MAPIFolder
    Set oApp = New Outlook.Application
    Set objNS = Application.GetNamespace("MAPI")
    Set objFolder = objNS.GetDefaultFolder(olFolderInbox)

    Dim pos1 As Long
    Dim pos2 As Long
    Dim pos3 As Long
    Dim pos4 As Long
    Dim pos5 As Long

    Dim msg As Outlook.MailItem

    For Each objItem In Application.ActiveExplorer.Selection

    Set msg = objItem.Forward

    msg.HTMLBody = objItem.HTMLBody
    msg.Subject = ("Test")

    pos1 = InStr(msg.HTMLBody, "Hi,")
        MsgBox ("pos1 " & pos1)
    pos2 = InStr(msg.HTMLBody, "Hello")
        MsgBox ("pos2 " & pos2)
    pos3 = InStr(msg.HTMLBody, "Good morning")
        MsgBox ("pos3 " & pos3)
    pos4 = InStr(msg.HTMLBody, "Kind regards")
        MsgBox ("pos4 " & pos4)

    If pos5 = 0 Then
        msg.To = "testemail@email.com"
        msg.Recipients.ResolveAll
        'msg.Send
        msg.Display
        Exit Sub
    End If

    If pos1 = 0 And pos2 = 0 And pos3 = 0 Then
        msg.To = "testemail@email.com"
        msg.Recipients.ResolveAll
        'msg.Send
        msg.Display
        Exit Sub
    End If


    If Not pos1 = 0 Then
        If Not pos4 = 0 Then
            msg.HTMLBody = Mid(msg.HTMLBody, pos1, pos4 - pos1 + Len("Kind regards"))
    End If
    ElseIf Not pos2 = 0 Then
        If Not pos4 = 0 Then
            msg.HTMLBody = Mid(msg.HTMLBody, pos2, pos4 - pos2 + Len("Kind regards"))
    End If
    ElseIf Not pos3 = 0 Then
        If Not pos4 = 0 Then
            msg.HTMLBody = Mid(msg.HTMLBody, pos3, pos4 - pos3 + Len("Kind regards"))
        End If
    End If

    msg.Display
    Next
End Sub

在 Outlook 中转发项目时不需要 re-assignt 邮件正文。当您手动执行此操作时,不会执行以下操作:

msg.HTMLBody = objItem.HTMLBody

仅供参考 Outlook 对象模型提供了三种处理项目正文的主要方式:

  1. Body.
  2. HTMLBody.
  3. Word 编辑器。 Inspector WordEditor 属性 class returns 表示邮件正文的 Word 文档实例。

有关详细信息,请参阅 Chapter 17: Working with Item Bodies