Search code examples
searchmailkitmimekit

Search for emails in MailKit not with the SearchQuery method but with simple text string criterias


Mailkit.SearchQuery provides a very powerful search system for finding emails with various parameters. But I want to make a research getting the criteria from a simple text string, to give the user the capability to do complex search by his own.

So I DONT'T want to do this:

var query = SearchQuery.DeliveredAfter(DateTime.Parse("2021-10-06"))
            .And(SearchQuery.FromContains("mailer-daemon@myprovider.it"));

but I want to do this:

string query = "SENTSINCE 2021-10-06 FROM mailer-daemon@myprovider.it";

The problem is that inbox is ImailFolder object (which doesn't have Search method with simple text string parameter overload) and not ImapFolder object (which instead got it!). How can I do?

static void ReadMsgs(Options opts)
    {
        using (var client = new ImapClient(new ProtocolLogger("imap.log")))
        {
            client.Connect(opts.Host, opts.Port, opts.UseSSL);
            client.Authenticate(opts.UserName, opts.Password);

            var inbox = client.Inbox;
            inbox.Open(FolderAccess.ReadOnly);
            
            Console.WriteLine("Total messages: {0}", inbox.Count);
            Console.WriteLine("Recent messages: {0}", inbox.Recent);


            // let's try searching for some messages...
            Console.WriteLine("Search in progress...");

            // this is a functional query based on SearchQuery
            //var query = SearchQuery.DeliveredAfter(DateTime.Parse("2021-10-06"))
            //    .And(SearchQuery.FromContains("mailer-daemon@myprovider.it"));

            // this is the code I would like to integrate based on a IMAP UID SEARCH text string
            //string query = "SENTSINCE 2021-10-06 FROM mailer-daemon@myprovider.it";
            foreach (var uid in inbox.Search(query))
            {
                var message = inbox.GetMessage(uid);
                Console.WriteLine("{0}|{1}|{2}|{3}|{4}", uid, message.Date, message.From, message.To,message.Subject);
            }

            client.Disconnect(true);
        }
    }

Solution

  • You can just cast from the IMailFolder to the ImapFolder.

    var inbox = (ImapFolder) client.Inbox;
    

    All IMailFolders returned by the ImapClient are ImapFolders.