Get shared folders from IMAP

This article describes how to get shared folder list from your IMAP server using Mail.dll IMAP component for .NET.

Shared folder names usually start with ‘#’ character. This is not a rule, but it’s very common.

IMAP server when asked for all folder list should return also shared folders.

Here’s the unit test code that shows this:

List<folderInfo> allFolders = client.GetFolders();
CollectionAssert.Contains(allFolders.Select(x => x.Name), "#Public.PublicFolder1");
CollectionAssert.Contains(allFolders.Select(x => x.Name), "#Public");

If you want to list only shared folders you’ll need to use IMAP’s NAMESPACE command. Imap.GetNamespaces() method returns Namespaces class which contains information about personal, shared and other users namespaces:

// C# version

using (Imap client = new Imap())
{
    client.Connect("server");
    client.Login("user", "password");

    Namespaces namespaces = client.GetNamespaces();

    // List shared folders in all shared namespaces
    foreach (NamespaceInfo space in namespaces.Shared)
    {
        List<folderInfo> sharedFolders = client.GetFolders(space.Name);
        sharedFolders.ForEach(x => Console.WriteLine(x.Name));
    }

    client.Close();
}
' VB.NET version

Using client As New Imap()
	client.Connect("server")
	client.Login("user", "password")

	Dim namespaces As Namespaces = client.GetNamespaces()

	' List shared folders in all shared namespaces
	For Each space As NamespaceInfo In namespaces.[Shared]
		Dim sharedFolders As List(Of FolderInfo) = client.GetFolders(space.Name)
		sharedFolders.ForEach(Function(x) Console.WriteLine(x.Name))
	Next

	client.Close()
End Using

The above code lists all public folders available for the currently logged-in user:

#Public.PublicFolder1
#Public.PublicFolder2
#Public

Please note that server will not let you select some folders. In the example above the user can not select ‘#Public’ folder. You can use FolderInfo.CanSelect property to check if the user is allowed to select the folder.

You can download Mail.dll IMAP library for .NET here

Tags: , , ,

Questions?

Consider using our Q&A forum for asking any questions.