Example usage for javax.mail Folder getFolder

List of usage examples for javax.mail Folder getFolder

Introduction

In this page you can find the example usage for javax.mail Folder getFolder.

Prototype

public abstract Folder getFolder(String name) throws MessagingException;

Source Link

Document

Return the Folder object corresponding to the given name.

Usage

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void createInitialIMAPTestdata(final Properties props, final String user, final String password,
        final int count, final boolean deleteall) throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);//from   w w w . ja va 2  s .c o  m
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

        deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

        if (testroot.exists()) {
            testroot.delete(true);
        }

        final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
        if (testrootenamed.exists()) {
            testrootenamed.delete(true);
        }

    }

    if (!testroot.exists()) {

        testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testroot.open(Folder.READ_WRITE);

        testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testrootl2.open(Folder.READ_WRITE);

    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        msgs[i] = message;

    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);

}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private Folder openFolder(cfSession _Session, Store popStore) throws cfmRunTimeException {
    try {/*ww  w .  ja v  a 2s  .c o  m*/
        Folder folder = popStore.getDefaultFolder();
        Folder popFolder = folder.getFolder("INBOX");
        popFolder.open(Folder.READ_WRITE);
        return popFolder;
    } catch (Exception E) {
        throw newRunTimeException(E.getMessage());
    }
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private Folder getUserInbox(Session session, String folderName) throws MessagingException {

    // Assertions.
    if (session == null) {
        String msg = "Argument 'session' cannot be null";
        throw new IllegalArgumentException(msg);
    }/*from  www  .  j ava 2 s . c o  m*/

    try {
        Store store = session.getStore();
        store.connect();

        if (log.isDebugEnabled()) {
            log.debug("Mail store connection established to get user inbox");
        }

        // Retrieve user's inbox folder
        Folder root = store.getDefaultFolder();
        Folder inboxFolder = root.getFolder(folderName);

        return inboxFolder;
    } catch (AuthenticationFailedException e) {
        throw new MailAuthenticationException(e);
    }

}

From source file:com.zotoh.maedr.device.PopIO.java

private boolean conn() {

    if (_pop == null || !_pop.isConnected())
        try {//from  w w w  .  ja  va  2 s.c  o m
            Session session = Session.getInstance(new Properties(), null);
            Provider[] ps = session.getProviders();
            Provider sun = null;
            Store st = null;
            Folder f = null;
            String uid = isEmpty(_user) ? null : _user;
            String pwd = isEmpty(_pwd) ? null : _pwd;
            String key = ST_POP3, sn = POP3;

            closePOP();

            if (_ssl) {
                key = ST_POP3S;
                sn = POP3S;
            }

            for (int i = 0; i < ps.length; ++i) {
                if (key.equals(ps[i].getClassName())) {
                    sun = ps[i];
                    break;
                }
            }

            if (!isEmpty(_storeImpl)) {
                // this should never happen , only in testing
                sun = new Provider(Provider.Type.STORE, "pop3", _storeImpl, "test", "1.0.0");
                sn = POP3;
            }

            session.setProvider(sun);
            st = session.getStore(sn);

            if (st != null) {
                st.connect(_host, _port, uid, pwd);
                f = st.getDefaultFolder();
            }

            if (f != null) {
                f = f.getFolder("INBOX");
            }

            if (f == null || !f.exists()) {
                throw new Exception("POP3: Cannot find inbox");
            }

            _pop = st;
            _fd = f;

        } catch (Exception e) {
            tlog().warn("", e);
            closePOP();
        }

    return _pop != null && _pop.isConnected();
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

/**
 * Set destination folder//w ww  .  ja va 2s.c  o m
 *
 * @param foldername
 *          destination foldername
 * @param createFolder
 *          flag create folder if needed
 * @throws KettleException
 */
public void setDestinationFolder(String foldername, boolean createFolder) throws KettleException {
    try {
        String[] folderparts = foldername.split("/");
        Folder f = this.getStore().getDefaultFolder();
        // Open destination folder
        for (int i = 0; i < folderparts.length; i++) {
            f = f.getFolder(folderparts[i]);
            if (!f.exists()) {
                if (createFolder) {
                    // Create folder
                    f.create(Folder.HOLDS_MESSAGES);
                } else {
                    throw new KettleException(
                            BaseMessages.getString(PKG, "MailConnection.Error.FolderNotFound", foldername));
                }
            }
        }
        this.destinationIMAPFolder = f;
    } catch (Exception e) {
        throw new KettleException(e);
    }
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

private Folder getRecursiveFolder(String foldername) throws MessagingException {
    Folder dfolder;
    String[] folderparts = foldername.split("/");
    dfolder = this.getStore().getDefaultFolder();
    // Open destination folder
    for (int i = 0; i < folderparts.length; i++) {
        dfolder = dfolder.getFolder(folderparts[i]);
    }//from   w  w w .j av  a 2  s.co m
    return dfolder;
}

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;/*  ww  w. ja v  a  2s. co m*/
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        if (!dst.create(src.getType())) {
            // might not be able to create a folder that holds both
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                // might only be able to create one type (Gmail)
                if (!dst.create(Folder.HOLDS_MESSAGES)) {
                    System.out.println("couldn't create " + dst.getFullName());
                    return;
                }
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;//from  www. ja v  a 2 s.c  o  m
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        try {
            if (!dst.create(src.getType())) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
        } catch (MessagingException mex) {
            // might not be able to create a folder that holds both
            if (src.getType() != (Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS))
                throw mex;
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

From source file:net.wastl.webmail.server.WebMailSession.java

public void addFolder(String toid, String name, boolean holds_messages, boolean holds_folders)
        throws MessagingException {
    Folder parent = getFolder(toid);
    Folder folder = parent.getFolder(name);
    if (!folder.exists()) {
        int type = 0;
        if (holds_messages) {
            type += Folder.HOLDS_MESSAGES;
        }// w w  w.j  a  v  a2  s  .c  om
        if (holds_folders) {
            type += Folder.HOLDS_FOLDERS;
        }
        folder.create(type);
    }
    // Should be called from FolderSetup Plugin
    //refreshFolderInformation();
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Refresh Information about folders./*  ww  w . j  a v a  2  s.c  o m*/
 * Tries to connect folders that are not yet connected.
 *
 * @doCount display message counts for user
 */
public void refreshFolderInformation(boolean subscribed_only, boolean doCount) {
    /* Right now, doCount corresponds exactly to subscribed_only.
     * When we add a user preference setting or one-time action,
     * to present messages from all folders, we will have
     * subscribed_only false and doCount true. */

    //log.fatal("Invoking refreshFolderInformation(boolean, boolean)",
    //new Throwable("Thread Dump"));  FOR DEBUGGING
    setEnv();
    if (folders == null)
        folders = new Hashtable<String, Folder>();
    Folder rootFolder = null;
    String cur_mh_id = "";
    Enumeration mailhosts = user.mailHosts();
    int max_depth = 0;
    int folderType;

    while (mailhosts.hasMoreElements()) {
        cur_mh_id = (String) mailhosts.nextElement();

        MailHostData mhd = user.getMailHost(cur_mh_id);

        URLName url = new URLName(mhd.getHostURL());

        Element mailhost = model.createMailhost(mhd.getName(), mhd.getID(), url.toString());

        int depth = 0;

        try {
            rootFolder = getRootFolder(cur_mh_id);

            try {
                rootFolder.setSubscribed(true);
            } catch (MessagingException ex) {
                // Only IMAP supports subscription
                log.warn("Folder.setSubscribed failed.  " + "Probably a non-supporting mail service: " + ex);
            }
        } catch (MessagingException ex) {
            mailhost.setAttribute("error", ex.getMessage());
            log.warn("Failed to connect and get Root folder from (" + url + ')', ex);
            return;
        }

        try {
            depth = getFolderTree(rootFolder.getFolder("INBOX"), mailhost, subscribed_only, doCount);
            log.debug("Loaded INBOX folders below Root to a depth of " + depth);
            String extraFolderPath = ((imapBasedir == null) ? "~" : imapBasedir) + mhd.getLogin();
            //String extraFolderPath = "/home/" + mhd.getLogin();
            Folder nonInboxBase = rootFolder.getFolder(extraFolderPath);
            log.debug("Trying extra base dir " + nonInboxBase.getFullName());
            if (nonInboxBase.exists()) {
                folderType = nonInboxBase.getType();
                if ((folderType & Folder.HOLDS_MESSAGES) != 0) {
                    // Can only Subscribe to Folders which may hold Msgs.
                    nonInboxBase.setSubscribed(true);
                    if (!nonInboxBase.isSubscribed())
                        log.error("A bug in JavaMail or in the server is " + "preventing subscription to '"
                                + nonInboxBase.getFullName() + "' on '" + url
                                + "'.  Folders will not be visible.");
                }
                int extraDepth = extraDepth = getFolderTree(nonInboxBase, mailhost, subscribed_only, doCount);
                if (extraDepth > depth)
                    depth = extraDepth;
                log.debug("Loaded additional folders from below " + nonInboxBase.getFullName()
                        + " with max depth of " + extraDepth);
            }
        } catch (Exception ex) {
            if (!url.getProtocol().startsWith("pop"))
                mailhost.setAttribute("error", ex.getMessage());
            log.warn("Failed to fetch child folders from (" + url + ')', ex);
        }
        if (depth > max_depth)
            max_depth = depth;
        model.addMailhost(mailhost);
    }
    model.setStateVar("max folder depth", (1 + max_depth) + "");
}