-1

using VB I would like to be able to start search from specific mail subfolder for emails by date and subject and return all mail items, this is what I have put together so far

As some items land in 'Other' in outlook365 need to also be able to search for them

Dim searchFilterCollection As List(Of SearchFilter) = New List(Of SearchFilter)()

Dim searchdate As DateTime = New DateTime(2019, 11, 19) 'Year, month, day
Dim greaterthanfilter As SearchFilter = New SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, searchdate)
Dim lessthanfilter As SearchFilter = New SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, searchdate.AddDays(1))

searchFilterCollection.Add(New SearchFilter.SearchFilterCollection(LogicalOperator.And, greaterthanfilter, lessthanfilter))
searchFilterCollection.Add(New SearchFilter.IsEqualTo(FolderSchema.DisplayName, "My Folder"))
  searchFilterCollection.Add(New SearchFilter.ContainsSubstring(ItemSchema.Subject, "Test Subject"))


    ' Create the search filter.
    Dim searchFilter As SearchFilter = New SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray())
    ' Create a view with a page size of 50.
    Dim view As New ItemView(50)

    'Identify the Subject and DateTimeReceived properties to return.
    'Indicate that the base property will be the item identifier
    view.PropertySet = (New PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived))

    ' Order the search results by the DateTimeReceived in descending order.
    view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending)

    ' Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.)
    view.Traversal = ItemTraversal.Shallow

    ' Send the request to search the Inbox and get the results.
    Dim findResults As FindItemsResults(Of Item) = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view)

    For Each item As Item In findResults
        Dim message As EmailMessage = EmailMessage.Bind(exchange, item.Id)
        Dim listitem As ListViewItem = New ListViewItem({message.DateTimeReceived.ToString(), message.From.Name.ToString() & "(" + message.From.Address.ToString() & ")", message.Subject, (If((message.HasAttachments), "Yes", "No")), message.Id.ToString()})
        lstMsg.Items.Add(listitem)
    Next

    If findResults.Items.Count <= 0 Then
        lstMsg.Items.Add("No Messages found!!")
    End If
JPS
  • 119
  • 1
  • 8
  • OK - that is what you have put together so far. Is there a question? Does it work? If it does not work, where is the error or unexpected output? – AJD Nov 19 '19 at 19:45
  • No it does not work, if I remve the 2 filters searchFilterCollection.Add(New SearchFilter.IsEqualTo(FolderSchema.DisplayName, "My Folder")) searchFilterCollection.Add(New SearchFilter.ContainsSubstring(ItemSchema.Subject, "Test Subject")) then it brings back emails from main inbox for current day, I would like to somehow get it so I can search a folder within inbox and its subfolders for a given subject(s), but I cant get it to start in a specified subfolder – JPS Nov 19 '19 at 19:52
  • Ive found a work around not ideal but does work, before this line Dim findResults As FindItemsResults(Of Item) = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view), I have a function call which gets me the folder details for a folder name, which use in this line as myfolder.id instead of wellknown folder, but you have to get the id for each folder, what I wanted was to set the staruing folder to search from to something and then only search that folder and all sub folders. – JPS Nov 19 '19 at 20:47
  • I have an issue where some email are landing in the 'Other' mailbox and not focused, How do I search in that mailbox, I have tried searching for folder other and also tried some other code I found which locates 'Allitems' folder, but still it does not show any emails that are sat in 'Other' – JPS Nov 23 '19 at 14:33
  • You can add that information to the Question through this link: https://stackoverflow.com/posts/58940977/edit - it will improve your question and improve your chances of getting an answer. – AJD Nov 23 '19 at 19:19
  • Found code that gets the All Items folder details which I can then use in the finditems – JPS Nov 24 '19 at 14:32
  • But you still have not edited your question. – AJD Nov 24 '19 at 18:27

1 Answers1

0

The below code allows me to search the All Items folder which covers the 'Other' folder, and retrieve only specific emails by date

NOTE : Found code on here : Exchange Web Services (EWS) FindItems within All Folders

Private Sub FindAllEmailByDate()

    ' ============== Setup Exchange connection =================================================================================
    'Add a valid EWS service end point here or user Autodiscover
    service.Url = New Uri("https://outlook.office365.com/EWS/Exchange.asmx")
    ' Connect by using the default credentials of the authenticated user.
    service.UseDefaultCredentials = False
    'Add a valid user credentials
    service.Credentials = New WebCredentials("EMAIL", "PASSWORD")

    'To address the SSL challenge
    ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateCertificate)


    ' ============== Gets ALLITEMS folder details =================================================================================
    Dim allFoldersType As ExtendedPropertyDefinition = New ExtendedPropertyDefinition(13825, MapiPropertyType.Integer)
    Dim rootFolderId As FolderId = New FolderId(WellKnownFolderName.Root)
    Dim folderView As FolderView = New FolderView(1000)
    folderView.Traversal = FolderTraversal.Shallow

    Dim searchFilter1 As SearchFilter = New SearchFilter.IsEqualTo(allFoldersType, "2")
    Dim searchFilter2 As SearchFilter = New SearchFilter.IsEqualTo(FolderSchema.DisplayName, "allitems")

    Dim searchFilterCollection1 As SearchFilter.SearchFilterCollection = New SearchFilter.SearchFilterCollection(LogicalOperator.[And])
    searchFilterCollection1.Add(searchFilter1)
    searchFilterCollection1.Add(searchFilter2)

    Dim FoldersResults As FindFoldersResults = service.FindFolders(rootFolderId, searchFilterCollection1, folderView)

    Dim allItemsFolder As Folder = Nothing

    If FoldersResults.Folders.Count > 0 Then allItemsFolder = FoldersResults.Folders(0)
    '========================================================================================================================

    Dim searchFilterCollection As List(Of SearchFilter) = New List(Of SearchFilter)()

    Dim searchdate As DateTime = Me.DateTimePicker1.Value.ToShortDateString
    ' Dim searchdate As DateTime = Date.Today

    ' Setup filter for date required to search within
    Dim greaterthanfilter As SearchFilter = New SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, searchdate)
    Dim lessthanfilter As SearchFilter = New SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, searchdate.AddDays(1))

    ' Loads found emails into listview
    If service IsNot Nothing Then
        lstMsg.Items.Clear()

        ' Create a view with a page size of 50.
        Dim view As New ItemView(50)

        'Identify the Subject and DateTimeReceived properties to return.
        'Indicate that the base property will be the item identifier
        view.PropertySet = (New PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived))

        ' Order the search results by the DateTimeReceived in descending order.
        view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending)

        ' Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.)
        view.Traversal = ItemTraversal.Shallow

        ' I only want to retrieve certain emails by subject line if arrrived
        Dim LPSearchFiles As String() = {"Agent Name", "Agent Group", "Full Groups"} ' etc

        For i = 0 To LPSearchFiles.Count - 1
            ' Clear Searchfilters
            searchFilterCollection.Clear()

            ' Add date filter
            searchFilterCollection.Add(New SearchFilter.SearchFilterCollection(LogicalOperator.And, greaterthanfilter, lessthanfilter))

            If LPSearchFiles(i).Contains("Agent Name") Or LPSearchFiles(i).Contains("Agent Group") Then
                ' The subject lines in these contain dates this will still bring them back if the subject line contains the wording
                searchFilterCollection.Add(New SearchFilter.ContainsSubstring(ItemSchema.Subject, LPSearchFiles(i)))
            Else
                ' This brings back only if exact match
                searchFilterCollection.Add(New SearchFilter.IsEqualTo(ItemSchema.Subject, LPSearchFiles(i)))
            End If

            ' Create the search filter.
            Dim searchFilter As SearchFilter = New SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray())

            ' Send the request to search the Inbox and get the results.
            Dim findResults As FindItemsResults(Of Item) = service.FindItems(allItemsFolder.Id, searchFilter, view)

            ' adds found emails to listview
            For Each item As Item In findResults
                Dim message As EmailMessage = EmailMessage.Bind(service, item.Id)
                Dim listitem As ListViewItem = New ListViewItem({message.DateTimeReceived.ToString(), message.From.Name.ToString() & "(" + message.From.Address.ToString() & ")", message.Subject, (If((message.HasAttachments), "Yes", "No")), message.Id.ToString()})
                lstMsg.Items.Add(listitem)
            Next
        Next i
    End If
End Sub

Private Function ValidateCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
    'Return True to force the certificate to be accepted.
    Return True
End Function
JPS
  • 119
  • 1
  • 8