在IMAP中创建文件夹不起作用

时间:2009-08-18 08:14:43

标签: java email gmail imap message

我正在努力在IMAP中创建一个文件夹(我正在使用gmail)

以下是我到目前为止的尝试:

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通过:“test 123”

输出:文件夹创建为Inbox / test123

我应该在这一行做什么: 文件夹defaultFolder = store.getFolder(“收件箱”); ??

我也在这里发布了同样的问题: http://www.coderanch.com/t/458722/Sockets-Internet-Protocols/java/creating-folders-IMAP-does-not

1 个答案:

答案 0 :(得分:17)

这是正确的代码:

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;   
}