0

Every time the mail is received, I want to print out a specific word in a body of email:

---------------------------------Body of email-------------------------------------

Sender Name: John

Sender's Address: john@sample-mail.com

Subject: Mail Subject from John <----- the line that I want to get

--------------------------------------End------------------------------------------

My Code:

Private WithEvents olItems As Outlook.Items


Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

End Sub

Private Sub Application_Startup()

  Dim olApp As Outlook.Application
  Dim olNS As Outlook.NameSpace

  Set olApp = Outlook.Application
  Set olNS = olApp.GetNamespace("MAPI")
  Set olItems = olNS.GetDefaultFolder(olFolderInbox).Folders("Watchlisted").Items

End Sub

Private Sub olItems_ItemAdd(ByVal Item As Object)
  Dim BodySubjLine As String, BodySubj As Variant
  
  Dim olMail As Outlook.MailItem
  Dim olAtt As Outlook.Attachment
  
  Set olMail = Item
  
  BodySubj = Split(olMail.Body, vbNewLine)
  BodySubjLine = Trim(BodySubj(2))
  
  Debug.Print BodySubjLine 
  
  Set olMail = Nothing

End Sub


Expected output:

Subject: Mail Subject from John

The output I get gives nothing at all

  • 1
    What does `Debug.Print UBound(BodySubj)` get you? You don't see any error? Try looping over `BodySubj` and printing each element along with its index, so you can figure out which one you want. It's possible you may want to use `vbCrLf` for the Split, instead of `vbLf` – Tim Williams Jul 23 '21 at 17:40
  • ```Debug.Print UBound(BodySubj)``` does nothing though, but the looping did give me an idea. Thx :) – Dunno dotcom Jul 26 '21 at 09:21
  • 1
    It doesn't do nothing - the output should be in the Immediate window in the VB editor. – Tim Williams Jul 26 '21 at 15:25
  • Another method https://stackoverflow.com/questions/20001670/search-structured-text-in-outlook-body – niton Nov 22 '21 at 17:41

2 Answers2

1

You could use breakpoints to debug the code.

Instead of

BodySubj = Split(olMail.Body, vbNewLine)

Use

BodySubj = Split(olMail.Body, Chr(10) & Chr(13))
Elio Fernandes
  • 1,335
  • 2
  • 14
  • 29
1

Instead of relying on message body lines you can use regular expressions to extract the exact substrings, read more about that:

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45