views:

230

answers:

1

Hi,

I am trying hard to create a folder in IMAP (I am using gmail)

Here is what i have attempted so far:

public boolean createFolder(String folderName) throws MessagingException
{
    store = session.getStore("imap");
    System.out.println("connecting store..");
    store.connect("imap.gmail.com", 993, "[email protected]", "password");
    System.out.println("connected !");

    //using store.getDefaultFolder(); shows error : "folder cannot contain messages"
    Folder defaultFolder = store.getFolder("Inbox");

    return createFolder(defaultFolder, folderName);
}

private boolean createFolder(Folder parent, String folderName)
{
    boolean isCreated = true;

    try
    {
        parent.open(Folder.READ_WRITE);
        System.out.println("adding listeners...");
        parent.addFolderListener(myMailFolderListener);
        System.out.println("creating a folder ....");
        Folder testFolder = parent.getFolder(folderName);

        isCreated = testFolder.create(Folder.HOLDS_MESSAGES);
        System.out.println("created: " + isCreated);
        parent.close(true);
    } catch (Exception e)
    {
        System.out.println("Error creating folder: " + e.getMessage());
        isCreated = false;
    }
    return isCreated;
}

foldername passed: "test 123"

output: folder is created as Inbox/test123

what should i do in this line: Folder defaultFolder = store.getFolder("Inbox"); ??

I have also posted this same question here: http://www.coderanch.com/t/458722/Sockets-Internet-Protocols/java/creating-folders-IMAP-does-not

+1  A: 

Here is the correct code :

public boolean createFolder(String folderName) throws MessagingException   
{   
    store = session.getStore("imap");   
    System.out.println("connecting store..");   
    store.connect("imap.gmail.com", 993, "[email protected]", "password");   
    System.out.println("connected !");   
    Folder defaultFolder = store.getDefaultFolder();   
    return createFolder(defaultFolder, folderName);   
}   

/*  
 * Note that in Gmail folder hierarchy is not maintained.  
 * */  
private boolean createFolder(Folder parent, String folderName)   
{   
    boolean isCreated = true;   

    try  
    {   
        Folder newFolder = parent.getFolder(folderName);   
        isCreated = newFolder.create(Folder.HOLDS_MESSAGES);   
        System.out.println("created: " + isCreated);   

    } catch (Exception e)   
    {   
        System.out.println("Error creating folder: " + e.getMessage());   
        e.printStackTrace();   
        isCreated = false;   
    }   
    return isCreated;   
}
Salvin Francis