creating folders in IMAP does not work

倾然丶 夕夏残阳落幕 提交于 2019-12-10 03:52:04

问题


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, "something@gmail.com", "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:


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, "something@gmail.com", "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;   
}


来源:https://stackoverflow.com/questions/1292488/creating-folders-in-imap-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!