Search code examples
c#.netimapmailkit

Is there a way to recursive searching folders in Mailkit?


Hope to not get boring with my Mailkit questions but I prefer asking them here in order to help others in the future if they need this help as well.

I need a method for searching a folder. I basically check if it exists and I'm intended to obviously open in if I need to work on it. The thing is that depending on the mailserver this could get a little messy because not every mailserver allows to create folders on the first level and so on (sigh).

Is there any way to recursively search for a folder and get its MailFolder object?

This is my actual code, which is pretty messy, "should" work in just level 2 folder and fails in carpeta.GetSubfolders() because I'm blowing my mind with folders, subfolers and where could I use the .Open method.

I actually have a method to check if the folder exists (the following one) and another to open it, so one problem calls to another :'D

private bool ExisteCarpeta(string nombreCarpetaABuscar)
{
    try
    {
        imap.Inbox.Open(FolderAccess.ReadOnly);
        var toplevel = imap.GetFolder(imap.PersonalNamespaces[0]);
        var carpetasNivel1 = toplevel.GetSubfolders();
        var carpeta = carpetasNivel1.FirstOrDefault(x => x.FullName.Equals(nombreCarpetaABuscar, StringComparison.InvariantCultureIgnoreCase));
            
        carpeta.GetSubfolders();
        return carpeta != null;
    }
    catch (Exception ex)
    {
        string mensaje = "Ha habido un problema comprando la existencia de la carpeta en el correo. \n";
        throw new Exception(mensaje, ex);
    }
}

Solution

  • You could do something like this:

    static IMailFolder FindFolder (IMailFolder toplevel, string name)
    {
        var subfolders = toplevel.GetSubfolders ().ToList ();
    
        foreach (var subfolder in subfolders) {
            if (subfolder.Name == name)
                return subfolder;
        }
    
        foreach (var subfolder in subfolders) {
            var folder = FindFolder (subfolder, name);
    
            if (folder != null)
                return folder;
        }
    
        return null;
    }
    

    You could use the above method like this:

    var toplevel = imap.GetFolder (imap.PersonalNamespaces[0]);
    var sent = FindFolder (toplevel, "Sent Items");