Finding Outlook mail messages from a specific sender

How to find Outlook mail messages from a specific sender.

Q:  Ray in New Zealand writes:  “I’m trying to link my Access db (Accommodation) to Outlook. I receive accommodation bookings from guests and would like to be able to click on a button on the guest data form which will take me to the emails which were received re their booking. I can’t seem to find anything which helps. Do you know of any way of doing this. I always include the guest’s email in the Access db.”

A:  You can do this by searching for mail messages with their SenderEmailAddress property equal to the email address stored in an Access table (picked up from the current form record).  You might also need to search for a specific subject line.  Here is some sample code that looks for messages from a specific email address with “Booking” in the subject line:

Private Sub cmdFindEmails_Click()

 

On Error GoTo ErrorHandler

  

   Dim appOutlook As New Outlook.Application

   Dim nms As Outlook.NameSpace

   Dim fldInbox As Outlook.MAPIFolder

   Dim msg As Outlook.MailItem

   Dim strEmail As String

   Dim itm As Object

  

   strEmail = Nz(Me![txtClientEmail].Value)

   If strEmail = “” Then

      MsgBox “No email selected; canceling”, vbExclamation

   End If

  

   Set nms = appOutlook.GetNamespace(“MAPI”)

   Set fldInbox = nms.GetDefaultFolder(olFolderInbox)

  

   For Each itm In fldInbox.Items

      If itm.Class = olMail Then

         Set msg = itm

         If msg.SenderEmailAddress = strEmail _

            And InStr(msg.Subject, “Booking”) > 0 Then

            msg.Display

         End If

      End If

   Next itm

  

ErrorHandlerExit:

   Exit Sub

 

ErrorHandler:

   MsgBox “Error No: ” & Err.Number & “; Description: ” & _

      Err.Description

   Resume ErrorHandlerExit

 

End Sub

 

See the frmClients form in the sample database Listbox Items (AA 172).mdb; this code runs from its cmdFindEmailsbutton.