How to get all folders name of gmail using ImapX lib? C#

4.9k Views Asked by At

How to get all folders name of gmail using ImapX lib? I read in http://hellowebapps.com/2010-02-09/imapx-net-library-to-manage-imap-folders/ but not found get all folder part.

3

There are 3 best solutions below

0
On

here is how you get the list of all folders...

        FolderCollection folders = client.GetFolders();
        foreach (Folder myfolder in folders)
        {
            MessageBox.Show(myfolder.Name);
        }

then use the name with:

ImapX.MessageCollection messages = client.Folders["Spam"].Search("ALL", true);

note that folder name is a case sensitive...

0
On

You can iterate the SubFolder collection and can get all of those gamail folders and thier path. An example:

var client = new ImapClient(...);
client.Connection();
client.LogIn(...);


foreach (var item in WalkFolderTree(client.Folders))
{

     Console.WriteLine(item.FolderPath);
 }

client.LogOut();

You have to custom implement the traversal code like:

public IEnumerable<Folder> WalkFolderTree(FolderCollection folders)
{
    foreach (var item in folders)
    {
        if (item.HasChildren)
        {
            WalkFolderTree(item.SubFolder);
        }
            yield return item;
    }

 }

Then it will list all of the folders like:

   INBOX
   ...
   [Gmail]
   [Gmail]/All Mail
   [Gmail]/Drafts
   [Gmail]/Sent Mail
   [Gmail]/Spam
   [Gmail]/Starred
   [Gmail]/Trash
0
On

Here's how:

        public List<string> getMailboxes(string emailAddress, string emailPassword)
    {
        var client = new ImapClient("imap.gmail.com", 993, true, true);
        if (client.Connect())
        {
            if (client.Login(emailAddress, emailPassword))
            {
                //get all parent folers
                var folders = client.Folders;

                foreach (var parentFolder in folders)
                {
                    //get parent folder path
                    var parentPath = parentFolder.Path;

                    //check if every parent folder has subfolder
                    if (parentFolder.HasChildren)
                    {
                        var subfolders = parentFolder.SubFolders;
                        foreach(var subfolder in subfolders)
                        {
                            var subPath = subfolder.Path;
                        }
                    }
                }
            }
        }
    }