Example usage for javax.mail Folder HOLDS_MESSAGES

List of usage examples for javax.mail Folder HOLDS_MESSAGES

Introduction

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

Prototype

int HOLDS_MESSAGES

To view the source code for javax.mail Folder HOLDS_MESSAGES.

Click Source Link

Document

This folder can contain messages

Usage

From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

protected void readFolder(Folder folder) throws MessagingException, IOException, SearchLibException {
    if (folder == null)
        return;//from  w  ww  .j a v  a  2s . c  o  m
    if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0)
        readMessagesFolder(folder);
    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0)
        readHoldsFolder(folder);
}

From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

protected void checkFolder(Folder folder, PrintWriter pw)
        throws MessagingException, IOException, SearchLibException {
    if (folder == null)
        return;//from  w ww  . j a v  a2  s  .  c o m
    if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
        folder.open(Folder.READ_ONLY);
        try {
            pw.print("Folder ");
            pw.print(folder.getName());
            pw.print(": ");
            pw.print(folder.getMessageCount());
            pw.println(" msgs(s).");
        } finally {
            folder.close(false);
        }
    }
    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        Folder[] folders = folder.list();
        if (folders != null)
            for (Folder f : folders)
                checkFolder(f, pw);
    }
}

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from  www . ja va 2 s.  c om
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

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

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        collect(in, msg);

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

@Override
public ArrayList<FolderItem> getFolderTree() throws MessagingException {
    getLogger().debug("getFolderTree");

    assert (getMailSource() != null);

    ArrayList<FolderItem> folderItems = new ArrayList<FolderItem>();

    Store store = getJavamailStore();//from  ww w. j  a v  a 2  s  . c o m
    store.connect();
    Folder defaultFolder = store.getDefaultFolder();
    FolderItem item = new FolderItem();
    item.setIndex(0);
    item.setLevel(0);
    item.setName(defaultFolder.getName());
    item.setFullName(defaultFolder.getFullName());
    if ((defaultFolder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
        item.setMessageCount(defaultFolder.getMessageCount());
        item.setUnreadMessageCount(defaultFolder.getUnreadMessageCount());
        item.setNewMessageCount(defaultFolder.getNewMessageCount());
    }
    Folder[] folders = defaultFolder.list("*");
    if (ArrayUtils.isEmpty(folders)) {
        folders = defaultFolder.list();
    }

    getLogger().debug("Found folders {}", ArrayUtils.toString(folders));
    int index = 1;
    int level = 1;
    // TODO not really managing folders here, just listing them
    for (Folder folder : folders) {

        item = new FolderItem();
        item.setIndex(index);
        item.setLevel(level);
        item.setName(folder.getName());
        item.setFullName(folder.getFullName());
        if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
            item.setMessageCount(folder.getMessageCount());
            item.setUnreadMessageCount(folder.getUnreadMessageCount());
            item.setNewMessageCount(folder.getNewMessageCount());
            folderItems.add(item);
        }
    }

    store.close();

    return folderItems;

}

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;/*from   w w  w.  j  a v a 2  s.  com*/
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

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

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        collect(in, msg);

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder. Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.xwiki.contrib.mail.internal.DefaultMailReader.java

@Override
public ArrayList<FolderItem> getFolderTree() throws MessagingException {
    assert (getMailSource() != null);
    assert (getMailSource().getHostname() != null);

    ArrayList<FolderItem> folderItems = new ArrayList<FolderItem>();
    store = null;// w  w w.  ja  va 2s.c o m
    boolean isGmail = getMailSource().getHostname() != null
            && getMailSource().getHostname().endsWith(".gmail.com");

    logger.info("Listing folders for " + getMailSource().getHostname());

    this.session = createSession(getMailSource().getProtocol(), getMailSource().getAdditionalProperties(),
            isGmail, getMailSource().isAutoTrustSSLCertificates());

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

    // Connect to the mail account
    store.connect(getMailSource().getHostname(), getMailSource().getPort(), getMailSource().getUsername(),
            getMailSource().getPassword());
    Folder defaultFolder = store.getDefaultFolder();
    FolderItem item = new FolderItem();
    item.setIndex(0);
    item.setLevel(0);
    item.setName(defaultFolder.getName());
    item.setFullName(defaultFolder.getFullName());
    if ((defaultFolder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
        item.setMessageCount(defaultFolder.getMessageCount());
        item.setUnreadMessageCount(defaultFolder.getUnreadMessageCount());
        item.setNewMessageCount(defaultFolder.getNewMessageCount());
    }
    Folder[] folders = defaultFolder.list("*");
    int index = 1;
    int level = 1;
    // TODO not really managing folders here, just listing them
    for (Folder folder : folders) {

        item = new FolderItem();
        item.setIndex(index);
        item.setLevel(level);
        item.setName(folder.getName());
        item.setFullName(folder.getFullName());
        if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
            item.setMessageCount(folder.getMessageCount());
            item.setUnreadMessageCount(folder.getUnreadMessageCount());
            item.setNewMessageCount(folder.getNewMessageCount());
            folderItems.add(item);
        }
    }

    store.close();

    return folderItems;

}

From source file:com.funambol.email.items.manager.ImapEntityManager.java

/**
 * deletes an email/*from w w w.  j  av a 2  s  .  c om*/
 *
 * @param parentId String
 * @param mailId String
 * @param GUID String
 * @param serverItems map with all in the Mail Server CrcSyncItemsInfo
 * @param source_uri  String
 * @param principalId long
 * @throws EntityException
 */
public void removeEmail(String parentId, String mailId, String GUID, Map serverItems, String username,
        String source_uri, long principalId) throws EntityException {

    String fullpath = null;

    try {
        fullpath = this.ied.getFullPathFromFID(parentId, source_uri, principalId, username);
    } catch (EntityException e) {
        throw new EntityException(e);
    }

    if (log.isTraceEnabled()) {
        log.trace("remove item in FID: " + fullpath + " with FMID: " + mailId);
    }

    if (fullpath != null) {
        if (parentId.equalsIgnoreCase(Def.FOLDER_INBOX_ID)) {
            try {

                // INBOX

                timeStart = System.currentTimeMillis();

                IMAPFolder inbox = this.imsw.folderInboxOpened;
                long uid = Long.parseLong(mailId);

                if (!inbox.isOpen()) {
                    inbox.open(javax.mail.Folder.READ_WRITE);
                }

                Message message = inbox.getMessageByUID(uid);
                IMAPFolder trashFolder = this.imsw.getTrashFolder();

                //
                // If the trash folder does not exists, then create it.
                //
                if (!trashFolder.exists()) {

                    if (log.isTraceEnabled()) {
                        log.trace("Trash folder does not exist. Creating Trash folder with path "
                                + trashFolder.getFullName());
                    }

                    if (trashFolder.create(Folder.HOLDS_MESSAGES)) {
                        trashFolder.open(Folder.READ_WRITE);
                    }
                }

                if (message != null) {
                    if (message.isExpunged()) {
                        //
                        // GMail mail server sometimes says an email is expunged
                        // even if it has not been previously deleted.
                        //
                        // Workaround:
                        //
                        // - such behaviour seems to appear after the first time
                        //   IMAPFolder.copyMessage method is executed on an open 
                        //   folder.
                        //
                        //   More precisely: the first time method is executed,
                        //   the given message is moved correctly; each of 
                        //   the subsequent execution could work correctly
                        //   or not.
                        // 
                        // - So: reopen the inbox folder (as: "nothing has
                        //   happened"), extract the message, call copyMessage
                        //   with that message.
                        //

                        if (inbox.isOpen()) {
                            //
                            // close folder expunging all emails to be expunged 
                            // in order to reset state of each email
                            //
                            inbox.close(true);
                            inbox.open(Folder.READ_WRITE);
                        }

                        message = ((IMAPFolder) inbox).getMessageByUID(uid);
                    }

                    //
                    // Following check: message != null is needed in the case
                    // message was expunged (see above).
                    //
                    if (message != null) {

                        // if TRASH folder exists, then copy email to TRASH folder
                        if (trashFolder.exists()) {
                            this.ied.copyEmail(inbox, trashFolder, uid);
                        }

                        //
                        // - With some mail servers the copyEmail method
                        //   copies the original message in the destination
                        //   folder and leaves the original one in the source
                        //   one.
                        // - Other mail servers move the message from the
                        //   source folder to the destination folder; thus
                        //   the original message cannot be deleted from the
                        //   source folder, since it has been already deleted. 
                        //
                        // For example: consider the Gmail mail server; when
                        // moving an email from the INBOX folder to the default
                        // trash folder, the copy operation will automatically 
                        // delete and expunge the original message from the
                        // source folder; note also that this behavior does
                        // not happen when destination folder is not the default
                        // trash folder).
                        //
                        if (!message.isExpunged()) {
                            // remove email from inbox folder
                            this.ied.removeEmail(inbox, uid);
                        }
                    }
                }

                // remove from Cache Inbox Table
                this.ied.removeEmailInDB(username, Def.PROTOCOL_IMAP, GUID);

                // remove serverItemsList
                this.ied.removeItemInServerItems(GUID, serverItems);

                timeStop = System.currentTimeMillis();
                if (log.isTraceEnabled()) {
                    log.trace("removeItem Execution Time: " + (timeStop - timeStart) + " ms");
                }
            } catch (MessagingException e) {
                throw new EntityException(e);
            } catch (EntityException e) {
                throw new EntityException(e);
            } catch (EmailAccessException e) {
                throw new EntityException(e);
            }
        } else {

            // SENT - OUTBOX - DRAFTS - TRASH

            IMAPFolder f = null;

            EntityException finalExc = null;

            try {

                timeStart = System.currentTimeMillis();
                // rest of the folders
                f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath);

                if (f.exists()) {

                    if (!f.isOpen()) {
                        f.open(Folder.READ_WRITE);
                    }

                    // remove email from mail server
                    this.ied.removeEmail(f, Long.parseLong(mailId));

                    // remove serverItemsList
                    this.ied.removeItemInServerItems(GUID, serverItems);

                }

            } catch (MessagingException me) {
                throw new EntityException(me);
            } catch (EntityException e) {
                throw new EntityException(e);
            } finally {
                if (f != null) {
                    try {
                        if (f.isOpen()) {
                            f.close(true);
                            timeStop = System.currentTimeMillis();
                            if (log.isTraceEnabled()) {
                                log.trace("removeItem Execution Time: " + (timeStop - timeStart) + " ms");
                            }
                        }
                    } catch (MessagingException me) {
                        throw new EntityException(me);
                    }
                }
            }
        }
    }
}

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);/*www  .j a  v a 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:edu.stanford.muse.email.ImapPopEmailStore.java

/** recursively collect all folder names under f into list */
private void collect_folder_names(Store store, List<FolderInfo> list, Folder f) throws MessagingException {
    // ignore hidden files
    if (f.getFullName().startsWith("."))
        return;//ww w . j a v  a  2s .c om
    if (f.getFullName().indexOf("/.") >= 0 || f.getFullName().indexOf("\\.") >= 0)
        return;

    // hack for csl-mail which takes too long to return all the folders
    if (connectOptions.server.startsWith("csl-mail") && f.getFullName().indexOf("/") >= 0)
        return;

    // TOFIX: apparently imap folders can have both messages and children
    Folder f_children[] = null;
    boolean hasMessages = true, hasChildren = false;
    boolean isPop = "pop3".equals(connectOptions.protocol) || "pop3s".equals(connectOptions.protocol);

    if (!isPop) {
        // if its imap, check for children
        hasChildren = (f.getType() & Folder.HOLDS_FOLDERS) != 0;
        hasMessages = (f.getType() & Folder.HOLDS_MESSAGES) != 0;
    }

    if (hasMessages) {
        folderBeingScanned = f.getFullName();
        Pair<Folder, Integer> pair = openFolder(store, f.getFullName());
        int count = pair.getSecond();
        if (count != -1)
            pair.getFirst().close(false);

        //         System.out.println ("full name = " + Util.blur(f.getFullName()) + " count = " + count);

        list.add(new FolderInfo(getAccountID(), f.getFullName(), f.getFullName(), count));
        folderBeingScanned = null;
    }

    if (hasChildren) {
        f_children = f.list();
        for (Folder child : f_children)
            collect_folder_names(store, list, child);
    }
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void fetch(final Folder folder) throws MessagingException, IOException {

    if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) {
        logger.warn("Folder {} cannot hold messages", folder.getFullName());
        return;//from   www.  j a  v a2  s . c om

    }

    final int messageCount = folder.getMessageCount();

    final UIDFolder uidfolder = (UIDFolder) folder;
    final long servervalidity = uidfolder.getUIDValidity();
    final RiverState riverState = stateManager.getRiverState(folder);
    final Long localvalidity = riverState.getUidValidity();

    logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount);

    logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity);

    if (localvalidity == null || localvalidity.longValue() != servervalidity) {

        logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity);

        if (localvalidity != null) {
            mailDestination.clearDataForFolder(folder.getFullName());
        }

        final ProcessResult result = process(messageCount, 1, folder.getFullName());

        riverState.setLastCount(result.getProcessedCount());

        if (result.getProcessedCount() > 0) {
            riverState.setLastIndexed(new Date());
        }

        if (result.getProcessedCount() > 0) {
            riverState.setLastTook(result.getTook());
        }

        riverState.setLastSchedule(new Date());

        if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
            riverState.setLastUid(result.getHighestUid());
        }

        riverState.setUidValidity(servervalidity);
        stateManager.setRiverState(riverState);

        logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(),
                folder.getFullName());
        logger.debug("Processed result {}", result.toString());

    } else {

        if (messageCount == 0) {
            logger.debug("Folder {} is empty", folder.getFullName());
        } else {

            if (withFlagSync) {
                // detect flag change
                final Message[] flagMessages = folder.getMessages();
                folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID);

                for (final Message message : flagMessages) {
                    try {

                        final long uid = ((UIDFolder) message.getFolder()).getUID(message);

                        final String id = uid + "::" + message.getFolder().getURLName();

                        final int storedHashcode = mailDestination.getFlaghashcode(id);

                        if (storedHashcode == -1) {
                            // New mail which is not indexed yet
                            continue;
                        }

                        final int flagHashcode = message.getFlags().hashCode();

                        if (flagHashcode != storedHashcode) {
                            // flags change for this message, must update
                            mailDestination.onMessage(message);

                            if (logger.isDebugEnabled()) {
                                logger.debug("Update " + id + " because of flag change");
                            }
                        }
                    } catch (final Exception e) {
                        logger.error("Error detecting flagchanges for message "
                                + ((MimeMessage) message).getMessageID(), e);
                        stateManager.onError("Error detecting flagchanges", message, e);
                    }
                }
            }

            final long highestUID = riverState.getLastUid(); // this uid is
                                                             // already
                                                             // processed

            logger.debug("highestUID: {}", highestUID);

            final Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID);

            // msgnew.size is always >= 1
            if (highestUID > 0 && uidfolder.getUID(msgsnew[0]) <= highestUID) {
                // msgsnew = (Message[]) ArrayUtils.remove(msgsnew, 0);
            }

            if (msgsnew.length > 0) {

                logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName());

                final int start = msgsnew[0].getMessageNumber();

                final ProcessResult result = process(messageCount, start, folder.getFullName());

                riverState.setLastCount(result.getProcessedCount());

                if (result.getProcessedCount() > 0) {
                    riverState.setLastIndexed(new Date());
                }

                if (result.getProcessedCount() > 0) {
                    riverState.setLastTook(result.getTook());
                }

                riverState.setLastSchedule(new Date());

                if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
                    riverState.setLastUid(result.getHighestUid());
                }

                riverState.setUidValidity(servervalidity);
                stateManager.setRiverState(riverState);

                logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(),
                        folder.getFullName());
                logger.debug("Processed result {}", result.toString());
            } else {
                logger.debug("no new messages");
            }

        }
        // check for expunged/deleted messages

        final Set<Long> serverMailSet = new HashSet<Long>();

        final long oldmailUid = riverState.getLastUid();
        logger.debug("oldmailuid {}", oldmailUid);

        final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid);

        folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID);

        for (final Message m : msgsold) {
            try {
                final long uid = uidfolder.getUID(m);
                serverMailSet.add(uid);

            } catch (final Exception e) {
                stateManager.onError("Unable to handle old message ", m, e);
                logger.error("Unable to handle old message due to {}", e, e.toString());

                IMAPUtils.open(folder);
            }
        }

        final Set localMailSet = new HashSet(
                mailDestination.getCurrentlyStoredMessageUids(folder.getFullName(), false));

        logger.debug("Check now " + localMailSet.size() + " server mails for expunge");

        localMailSet.removeAll(serverMailSet);
        // localMailSet has now the ones that are not on server

        logger.info(
                localMailSet.size() + " messages were locally deleted, because they are expunged on server.");

        mailDestination.onMessageDeletes(localMailSet, folder.getFullName(), false);

    }

}