Example usage for javax.mail Folder exists

List of usage examples for javax.mail Folder exists

Introduction

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

Prototype

public abstract boolean exists() throws MessagingException;

Source Link

Document

Tests if this folder physically exists on the Store.

Usage

From source file:jp.mamesoft.mailsocketchat.Mail.java

public void run() {
    while (true) {
        try {//  w  w w . j  a v a2  s . c om
            System.out.println("????");
            Properties props = System.getProperties();

            // Get a Session object
            Session session = Session.getInstance(props, null);
            // session.setDebug(true);

            // Get a Store object
            Store store = session.getStore("imaps");

            // Connect
            store.connect("imap.gmail.com", 993, Mailsocketchat.mail_user, Mailsocketchat.mail_pass);
            System.out.println("??????");

            // Open a Folder
            Folder folder = store.getFolder("INBOX");
            if (folder == null || !folder.exists()) {
                System.out.println("IMAP??????");
                System.exit(1);
            }

            folder.open(Folder.READ_WRITE);

            // Add messageCountListener to listen for new messages
            folder.addMessageCountListener(new MessageCountAdapter() {
                public void messagesAdded(MessageCountEvent ev) {
                    Message[] msgs = ev.getMessages();

                    // Just dump out the new messages
                    for (int i = 0; i < msgs.length; i++) {
                        try {
                            System.out.println("?????");
                            InternetAddress addrfrom = (InternetAddress) msgs[i].getFrom()[0];
                            String subject = msgs[i].getSubject();
                            if (subject == null) {
                                subject = "";
                            }

                            Pattern hashtag_p = Pattern.compile("#(.+)");
                            Matcher hashtag_m = hashtag_p.matcher(subject);

                            if (subject.equals("#")) {
                                hashtag = null;
                            } else if (hashtag_m.find()) {
                                hashtag = hashtag_m.group(1);
                            }

                            String comment = msgs[i].getContent().toString().replaceAll("\r\n", " ");
                            comment = comment.replaceAll("\n", " ");
                            comment = comment.replaceAll("\r", " ");
                            JSONObject data = new JSONObject();
                            data.put("comment", comment);
                            if (hashtag != null) {
                                data.put("channel", hashtag);
                            }
                            if (!comment.equals("") && !comment.equals(" ") && !comment.equals("  ")) {
                                Mailsocketchat.socket.emit("say", data);
                                System.out.println("????");
                            }

                            //
                            if (subject.equals("push") || subject.equals("Push")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 2);
                                Mailsocketchat.push = true;
                                Mailsocketchat.repeat = false;
                                Mailsocketchat.address = addrfrom.getAddress();
                                repeatthread.cancel();
                                repeatthread = null;
                                System.out.println("?????");
                            } else if (subject.equals("fetch") || subject.equals("Fetch")
                                    || subject.equals("?")) {
                                Send(addrfrom.getAddress(), 3);
                                Mailsocketchat.push = false;
                                Mailsocketchat.repeat = false;
                                repeatthread.cancel();
                                repeatthread = null;
                                System.out.println("??????");
                            } else if (subject.equals("repeat") || subject.equals("Repeat")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 7);
                                Mailsocketchat.push = false;
                                Mailsocketchat.repeat = true;
                                Mailsocketchat.address = addrfrom.getAddress();
                                if (repeatthread == null) {
                                    repeatthread = new Repeat();
                                    repeat = new Timer();
                                }
                                repeat.schedule(repeatthread, 0, 30 * 1000);
                                System.out.println("?????");
                            } else if (subject.equals("list") || subject.equals("List")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 4);
                            } else if (subject.equals("help") || subject.equals("Help")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 5);
                            } else {
                                if (!Mailsocketchat.push && !Mailsocketchat.repeat) {
                                    Send(addrfrom.getAddress(), 0);
                                } else if (comment.equals("") || comment.equals(" ") || comment.equals("  ")) {
                                    Send(addrfrom.getAddress(), 5);
                                }
                            }
                        } catch (IOException ioex) {
                            System.out.println(
                                    "??????????");
                        } catch (MessagingException mex) {
                            System.out.println(
                                    "??????????");
                        }
                    }
                }
            });

            // Check mail once in "freq" MILLIseconds
            int freq = 1000; //??
            boolean supportsIdle = false;
            try {
                if (folder instanceof IMAPFolder) {
                    IMAPFolder f = (IMAPFolder) folder;
                    f.idle();
                    supportsIdle = true;
                }
            } catch (FolderClosedException fex) {
                throw fex;
            } catch (MessagingException mex) {
                supportsIdle = false;
            }
            for (;;) {
                if (supportsIdle && folder instanceof IMAPFolder) {
                    IMAPFolder f = (IMAPFolder) folder;
                    f.idle();
                } else {
                    Thread.sleep(freq); // sleep for freq milliseconds

                    // This is to force the IMAP server to send us
                    // EXISTS notifications. 
                    folder.getMessageCount();
                }
            }

        } catch (Exception ex) {
            System.out.println("??????????");
        }
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
* Return the {@link Folder} object corresponding to the given 
* {@link ImapGmailLabel} name. //from www. java  2s.co m
* Note that a {@link Folder} object is returned only if the named 
* {@link Folder} physically exist on the Store.
* 
* @param name the name of the folder
* @param store instance of Gmail {@link Store}
*/
private Folder getFolder(String name, final Store store) {
    if (store == null) {
        throw new GmailException("Gmail IMAP store cannot be null");
    }
    try {
        name = ((name == null) ? this.srcFolder : name);
        Folder folder = store.getFolder(name);
        if (folder.exists()) {
            return folder;
        }
    } catch (final Exception e) {
        throw new GmailException("ImapGmailClient failed getting " + "Folder: " + name, e);
    }

    throw new GmailException("ImapGmailClient Folder name cannot be null");
}

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.  j av a2  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:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java

protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException {

    logger.debug("fetch() - pattern: {}, folderName: {}", pattern, folderName);

    final Store store = Session.getInstance(props).getStore();
    store.connect(user, password);//from w ww.  j a  v  a  2  s .co  m

    try {
        for (final String fol : mailDestination.getFolderNames()) {
            if (store.getFolder(fol).exists()) {
                logger.debug("{} exists", fol);
            } else {
                logger.info(
                        "Folder {} does not exist on the server, will remove it (and its content) also locally",
                        fol);
                final RiverState riverState = stateManager.getRiverState(store.getFolder(fol));
                riverState.setExists(false);
                stateManager.setRiverState(riverState);

                try {
                    mailDestination.clearDataForFolder(fol);
                } catch (final Exception e) {
                    stateManager.onError("Unable to clean data for stale folder", store.getFolder(fol), e);
                }
            }
        }
    } catch (final IndexMissingException ime) {
        logger.debug(ime.toString());

    } catch (final Exception e) {
        logger.error("Error checking for stale folders", e);
    }

    final boolean isRoot = StringUtils.isEmpty(folderName);
    final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName);

    try {

        if (!folder.exists()) {
            logger.error("Folder {} does not exist on the server", folder.getFullName());
            return;
        }

        logger.debug("folderName: {} is root: {}", folderName, isRoot);

        /*if (logger.isDebugEnabled() && store instanceof IMAPStore) {
                
           IMAPStore imapStore = (IMAPStore) store;
           logger.debug("IMAP server capability info");
           logger.debug("IMAP4rev1: "
             + imapStore.hasCapability("IMAP4rev1"));
           logger.debug("IDLE: " + imapStore.hasCapability("IDLE"));
           logger.debug("ID: " + imapStore.hasCapability("ID"));
           logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS"));
           logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN"));
           logger.debug("NAMESPACE: "
             + imapStore.hasCapability("NAMESPACE"));
           logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY"));
           logger.debug("CONDSTORE: "
             + imapStore.hasCapability("CONDSTORE"));
           logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC"));
           logger.debug("STATUS: " + imapStore.hasCapability("STATUS"));
        }*/

        if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) {
            logger.info(folder.getFullName() + " does not match pattern " + pattern.toString());
            return;
        }

        IMAPUtils.open(folder);

        recurseFolders(folder, pattern);

    } finally {

        IMAPUtils.close(folder);
        IMAPUtils.close(store);

    }
}

From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java

protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException {
    logger.debug("fetch() - pattern: {}, folderName: {}, user: {}", pattern, folderName, user);

    final Store store = Session.getInstance(props).getStore();
    store.connect(user, password);/*www  .ja  va 2  s .  c  o  m*/

    if (deleteExpungedMessages) {

        try {
            for (final String fol : mailDestination.getFolderNames()) {
                if (store.getFolder(fol).exists()) {
                    logger.debug("{} exists for {}", fol, user);
                } else {
                    logger.info(
                            "Folder {} does not exist for {} on the server, will remove it (and its content) also locally",
                            user, fol);
                    final State riverState = stateManager.getRiverState(store.getFolder(fol));
                    riverState.setExists(false);
                    stateManager.setRiverState(riverState);

                    try {
                        mailDestination.clearDataForFolder(store.getFolder(fol));
                    } catch (final Exception e) {
                        stateManager.onError("Unable to clean data for stale folder for " + user,
                                store.getFolder(fol), e);
                    }
                }
            }
        } /*catch (final IndexMissingException ime) {
          logger.debug(ime.toString());
          //TODO 2.0 check
          } */ catch (final Exception e) {
            logger.error("Error checking for stale folders", e);
        }

    }

    final boolean isRoot = StringUtils.isEmpty(folderName);
    final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName);

    try {

        if (!folder.exists()) {
            logger.error("Folder {} does not exist on the server", folder.getFullName());
            return;
        }

        logger.debug("folderName: {} is root: {}", folderName, isRoot);

        /*if (logger.isDebugEnabled() && store instanceof IMAPStore) {
                
           IMAPStore imapStore = (IMAPStore) store;
           logger.debug("IMAP server capability info");
           logger.debug("IMAP4rev1: "
             + imapStore.hasCapability("IMAP4rev1"));
           logger.debug("IDLE: " + imapStore.hasCapability("IDLE"));
           logger.debug("ID: " + imapStore.hasCapability("ID"));
           logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS"));
           logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN"));
           logger.debug("NAMESPACE: "
             + imapStore.hasCapability("NAMESPACE"));
           logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY"));
           logger.debug("CONDSTORE: "
             + imapStore.hasCapability("CONDSTORE"));
           logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC"));
           logger.debug("STATUS: " + imapStore.hasCapability("STATUS"));
        }*/

        if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) {
            logger.debug(folder.getFullName() + " does not match pattern " + pattern.toString());
            return;
        }

        IMAPUtils.open(folder);

        recurseFolders(folder, pattern);

    } finally {

        IMAPUtils.close(folder);
        IMAPUtils.close(store);

    }
}

From source file:EmailBean.java

private void handleMessages(HttpServletRequest request, PrintWriter out) throws IOException, ServletException {

    HttpSession httpSession = request.getSession();
    String user = (String) httpSession.getAttribute("user");
    String password = (String) httpSession.getAttribute("pass");
    String popAddr = (String) httpSession.getAttribute("pop");

    Store popStore = null;//from ww w  . ja  va2 s. c  om
    Folder folder = null;

    if (!check(popAddr))
        popAddr = EmailBean.DEFAULT_SERVER;

    try {

        if ((!check(user)) || (!check(password)))
            throw new ServletException("A valid username and password is required to check email.");

        Properties properties = System.getProperties();

        Session session = Session.getDefaultInstance(properties);

        popStore = session.getStore("pop3");

        popStore.connect(popAddr, user, password);

        folder = popStore.getFolder("INBOX");

        if (!folder.exists())
            throw new ServletException("An 'INBOX' folder does not exist for the user.");

        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        int msgLen = messages.length;

        if (msgLen == 0)
            out.println("<h2>The INBOX folder does not yet contain any email messages.</h2>");

        for (int i = 0; i < msgLen; i++) {
            displayMessage(messages[i], out);
            out.println("<br /><br />");
        }

    } catch (Exception exc) {

        out.println("<h2>Sorry, an error occurred while accessing the email messages.</h2>");
        out.println(exc.toString());

    } finally {
        try {
            if (folder != null)
                folder.close(false);

            if (popStore != null)
                popStore.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.cubusmail.mail.imap.IMAPMailbox.java

public void renameFolder(String folderId, String folderName) throws MailFolderException {

    IMailFolder folder = getMailFolderById(folderId);
    try {//from   w  ww.  j a  va  2 s.  co  m
        String newName = folder.getId();
        if (newName.lastIndexOf(getFolderSeparator()) >= 0) {
            newName = newName.substring(0, newName.lastIndexOf(getFolderSeparator()) + 1) + folderName;
        } else {
            newName = folderName;
        }

        if (folder.isOpen()) {
            folder.close(false);
        }
        Folder newFolder = this.store.getFolder(newName);
        if (!newFolder.exists()) {
            folder.renameTo(newFolder);
        } else {
            throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_ALREADY_EXIST, null,
                    createMailFolder(newFolder));
        }
        loadMailFolder();
    } catch (MessagingException ex) {
        throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_RENAME, ex, folder);
    }
}

From source file:com.cubusmail.mail.imap.IMAPMailbox.java

public IMailFolder createFolder(String parentFolderId, String folderName) throws MailFolderException {

    try {// www.  ja  va 2  s.  c o  m

        String newFolderName = null;
        if (!StringUtils.isEmpty(parentFolderId)) {
            newFolderName = parentFolderId + getFolderSeparator() + folderName;
        } else {
            newFolderName = folderName;
        }

        Folder newFolder = this.store.getFolder(newFolderName);
        if (!newFolder.exists()) {
            logger.debug("Createing folder... " + newFolderName);
            newFolder.create(Folder.HOLDS_MESSAGES);
        } else {
            throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_ALREADY_EXIST, null);
        }
        loadMailFolder();

        return createMailFolder(newFolder);
    } catch (MessagingException ex) {
        throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_CREATE, ex);
    }
}

From source file:com.cubusmail.mail.imap.IMAPMailbox.java

public void moveFolder(String sourceFolderId, String targetFolderId) throws MailFolderException {

    IMailFolder sourceFolder = null;/*from   ww  w .  j  a v  a  2s.  c om*/
    IMailFolder targetFolder = null;

    try {
        String newFolderName;

        sourceFolder = getMailFolderById(sourceFolderId);
        targetFolder = getMailFolderById(targetFolderId);

        if (sourceFolder != null) {
            if (targetFolder == null) {
                newFolderName = sourceFolder.getName();
            } else {
                newFolderName = targetFolder.getId() + getFolderSeparator() + sourceFolder.getName();
            }

            if (sourceFolder.isOpen()) {
                sourceFolder.close(false);
            }
            if (targetFolder != null && targetFolder.isOpen()) {
                targetFolder.close(false);
            }

            Folder newFolder = this.store.getFolder(newFolderName);
            if (!newFolder.exists()) {
                sourceFolder.renameTo(newFolder);
            } else {
                throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_ALREADY_EXIST, null, sourceFolder);
            }
            loadMailFolder();
        }
    } catch (MessagingException e) {
        throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_MOVE, e, sourceFolder);
    }
}

From source file:com.cubusmail.server.mail.imap.IMAPMailbox.java

public IMailFolder renameFolder(String folderId, String folderName) throws MailFolderException {

    IMailFolder folder = getMailFolderById(folderId);
    try {// w w  w.ja va  2s.c  om
        String newName = folder.getId();
        if (newName.lastIndexOf(getFolderSeparator()) >= 0) {
            newName = newName.substring(0, newName.lastIndexOf(getFolderSeparator()) + 1) + folderName;
        } else {
            newName = folderName;
        }

        if (folder.isOpen()) {
            folder.close(false);
        }
        Folder newFolder = this.store.getFolder(newName);
        if (!newFolder.exists()) {
            if (!folder.renameTo(newFolder)) {
                throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_RENAME, null, folder);
            }
        } else {
            throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_ALREADY_EXIST, null,
                    createMailFolder(newFolder));
        }
        loadMailFolder();
        return createMailFolder(newFolder);
    } catch (MessagingException ex) {
        throw new MailFolderException(IErrorCodes.EXCEPTION_FOLDER_RENAME, ex, folder);
    }
}