Search code examples
c#imap

IMAP Selecting multi-worded mailboxes


I am trying to create my own Imap Library on C#, and so far I have been able to do about everything I have tried (connect, login, list, select, fetch, etc).

I am having problems, however, in selecting a mailbox that has multiple words in its name.

For example, the mailbox name "New Label" cannot be selected whereas "INBOX" is successfully selected.

0002 LIST "" "%"
* LIST (\HasNoChildren) "/" "INBOX"
* LIST (\HasNoChildren) "/" "New"
* LIST (\HasNoChildren) "/" "New Label"
* LIST (\HasChildren \Noselect) "/" "[Gmail]"
0002 OK Success

0003 SELECT INBOX
0003 OK [READ-WRITE] INBOX selected. (Success)

0004 SELECT New Label
0004 BAD Could not parse command

The IMAP specification (RFC 3501 5.1 Mailbox Naming) does not reference how this should be treated. It does mention internation naming 5.1.3, but it states that the US-ASCII printable characters represent themselves.

The answer to this question shows that the mailbox name should be sent with the space in it, but this is obviously not working in my case.

This is the code that I am using to create the command (which works fine with every command I have tried so far):

    public ResponseStatusEnum sendCommandReceiveResponse(out List<String> responseArray, string command, params string[] cmdParams)
    {
        ResponseStatusEnum response;
        if (command == null) throw new Exception("No command passed in to send to the server");
        // Increment the id before getting the id string
        m_nCommandId++;
        StringBuilder sbCommand = new StringBuilder(CommandId + " ");

        // Include the Imap command
        sbCommand.Append(command);

        //Include the parameters specific to the command
        for (int i = 0; i < cmdParams.Length; i++)
        {
            sbCommand.Append(" " + cmdParams[i]);
        }
        sbCommand.Append(ImapEol);

Solution

  • RFC 3501 does specify that, the first line of page 87 specifies that astring syntax is to be used. Astring is used for a lot of things in IMAP, and in this case it's just:

    0004 SELECT "New label"
    

    Do read the astring/string/nstring/literal productions in the syntax, you have to get them right in order to parse or generate IMAP beyond the hello-world stage. Or use a library if you want to outsource it, there are fine libraries on C#.