Example usage for javax.mail UIDFolder LASTUID

List of usage examples for javax.mail UIDFolder LASTUID

Introduction

In this page you can find the example usage for javax.mail UIDFolder LASTUID.

Prototype

long LASTUID

To view the source code for javax.mail UIDFolder LASTUID.

Click Source Link

Document

This is a special value that can be used as the end parameter in getMessagesByUID(start, end), to denote the UID of the last message in the folder.

Usage

From source file:uidmsgshow.java

public static void main(String argv[]) {
    long uid = -1;
    int optind;//www  .  ja v  a  2 s. c  om

    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("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println(
                    "Usage: uidmsgshow [-L url] [-T protocol] [-H host] [-U user] [-P password] [-f mailbox] [uid] [-v]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length)
            uid = Long.parseLong(argv[optind]);

        // Get a Properties object
        Properties props = System.getProperties();

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

        // 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();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        folder = folder.getFolder(mbox);
        if (!folder.exists()) {
            System.out.println(mbox + "  does not exist");
            System.exit(1);
        }

        if (!(folder instanceof UIDFolder)) {
            System.out.println("This Provider or this folder does not support UIDs");
            System.exit(1);
        }

        UIDFolder ufolder = (UIDFolder) folder;

        folder.open(Folder.READ_WRITE);
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (uid == -1) {
            // Attributes & Flags for ALL messages ..
            Message[] msgs = ufolder.getMessagesByUID(1, UIDFolder.LASTUID);

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE UID #" + ufolder.getUID(msgs[i]) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            System.out.println("Getting message UID: " + uid);
            Message m = ufolder.getMessageByUID(uid);
            if (m != null)
                dumpPart(m);
            else
                System.out.println("This Message does not exist on this folder");
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
    }
    System.exit(1);
}

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   w w  w  .  ja  va  2  s . c o m

    }

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

    }

}

From source file:de.saly.elasticsearch.importer.imap.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  w ww . ja v  a  2 s. c om*/

    }

    final int messageCount = folder.getMessageCount();

    final UIDFolder uidfolder = (UIDFolder) folder;
    final long servervalidity = uidfolder.getUIDValidity();
    final State 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);
        }

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

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

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

            if (highestUID < 1) {
                logger.error("highestUID: {} not valid, set it to 1", highestUID);
                highestUID = 1;
            }

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

            if (msgsnew.length > 0) {

                System.out.println("lastuid: " + uidfolder.getUID(msgsnew[msgsnew.length - 1]));

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

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

        if (deleteExpungedMessages) {

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

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

        }

    }

}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

protected int fetchFolder(IMAPFolder folder, EmailFolder repoFolder, boolean topFlag)
        throws MessagingException {
    int n = 0;/*from w  w w.j a va 2 s .  co m*/
    if (!topFlag) {
        if (logger.isDebugEnabled())
            logger.debug("Openning folder " + folder.getName());
        folder.open(Folder.READ_ONLY);
        List<EmailMessage> fetchedEmails = repoFolder.getEmails();
        long firstUID = 1;
        if (fetchedEmails.size() > 0) {
            firstUID = fetchedEmails.get(fetchedEmails.size() - 1).getUID() + 1;
        }
        Message[] messages = folder.getMessagesByUID(firstUID, UIDFolder.LASTUID);
        n = messages.length;
        for (int i = 0; i < messages.length; i++) {
            AlvexEmailMessage m = new AlvexEmailMessage((MimeMessage) messages[i], folder);
            if (m.getUID() < firstUID)
                continue;
            if (logger.isDebugEnabled())
                logger.debug("Fetched message " + Integer.toString((i + 1)) + "/"
                        + Integer.toString(messages.length) + " from folder " + folder.getName() + ": \""
                        + m.getSubject() + "\" from " + m.getFrom());
            Map<QName, Serializable> props = new HashMap<QName, Serializable>();
            props.put(AlvexContentModel.PROP_EMAIL_FROM, m.getFrom());
            props.put(AlvexContentModel.PROP_EMAIL_TO, m.getTo());
            props.put(AlvexContentModel.PROP_EMAIL_CC, (Serializable) m.getCC());
            props.put(AlvexContentModel.PROP_EMAIL_SUBJECT, m.getSubject());
            props.put(AlvexContentModel.PROP_EMAIL_IN_REPLY_TO, m.getInReplyTo());
            props.put(AlvexContentModel.PROP_EMAIL_SENT_DATE, m.getSentDate());
            props.put(AlvexContentModel.PROP_EMAIL_UID, m.getUID());
            props.put(AlvexContentModel.PROP_EMAIL_ID, m.getID());
            NodeRef messageNode = createNode(repoFolder.getNodeRef(), ContentModel.ASSOC_CONTAINS,
                    AlvexContentModel.TYPE_EMAIL_MESSAGE, props);
            writeContent(messageNode, m.getBody());
            for (EmailMessagePart att : m.getAttachments()) {
                // FIXME_ASAP: think about it more carefully
                String subj = m.getSubject();
                String fname = att.getFileName();
                if (fname.equals(subj + " (part 1).html"))
                    continue;
                if (logger.isDebugEnabled())
                    logger.debug("Creating attachment: " + att.getFileName());
                props.clear();
                props.put(AlvexContentModel.PROP_EMAIL_REAL_NAME, att.getFileName());
                // FIXME_ASAP: think about it more carefully
                props.put(ContentModel.PROP_NAME, att.getFileName());
                NodeRef attNodeRef = createNode(messageNode, AlvexContentModel.ASSOC_EMAIL_ATTACHMENTS,
                        AlvexContentModel.TYPE_EMAIL_ATTACHMENT, props);
                writeContent(attNodeRef, att);
            }
            for (EmailMessageEventListener l : listeners)
                if (l != null)
                    l.onNewMessageReceived(new EmailMessageImpl(messageNode, nodeService, contentService));
        }
        if (logger.isDebugEnabled())
            logger.debug("Closing folder " + folder.getName());
        folder.close(true);
    }
    for (EmailFolder f : repoFolder.getSubfolders())
        if (f.isFetchActive()) {
            fetchFolder((IMAPFolder) folder.getFolder(f.getName()), f, false);
        }
    return n;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Import messages/*from ww w. j  a  v  a2  s  . co  m*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info(i + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType());
            log.info("Received: " + msg.getReceivedDate());
            log.info("Sent: " + msg.getSentDate());
            log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() });
            com.ikon.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:com.openkm.util.MailUtils.java

/**
 * Import messages/*from  w  w w  .  jav a  2 s .co  m*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info("======= ======= {} ======= =======", i);
            log.info("Subject: {}", msg.getSubject());
            log.info("From: {}", msg.getFrom());
            log.info("Received: {}", msg.getReceivedDate());
            log.info("Sent: {}", msg.getSentDate());
            com.openkm.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:edu.stanford.muse.email.EmailFetcherStats.java

/**
 * Comment by @vihari//  w w w .jav  a2s. c  o m
 * Not sure what uid id and folder are,I think this code should be more predictable
 * The params begin idx and end idx are used for both uid filtering and Mbox message indexing.
 * does not make sense
 */
private Message[] openFolderAndGetMessages() throws MessagingException {
    if (folder == null)
        openFolderAndGetMessageCount();

    Message[] messages = null;
    if (folder == null)
        return messages;

    String descr = emailStore.getAccountID() + ":" + folder;
    boolean haveUID = false;
    int count = folder.getMessageCount();
    use_uid_if_available = (begin_msg_index == 1 && end_msg_index == count + 1);
    log.info("use_uid_if_available is set to " + use_uid_if_available);

    if (fetchConfig.filter != null && fetchConfig.filter.isActive()) {
        log.info("Issuing server side filters for " + fetchConfig.filter);
        boolean useReceivedDateTerms = descr.indexOf("yahoo.com") >= 0;
        messages = folder.search(fetchConfig.filter.convertToSearchTerm(useReceivedDateTerms));
    } else {
        // mbox provider claims to provide UIDFolder but the uids are bogus so we treat mboemailstore folders as not uidfolders
        boolean is_uid_folder = (folder instanceof UIDFolder) && !(emailStore instanceof MboxEmailStore);

        if (use_uid_if_available && is_uid_folder) {
            // for uidfolders, we want to update the last seen uid in the FolderInfo
            long uid = archive.getLastUIDForFolder(emailStore.getAccountID(), folder_name());
            if (uid > 0) {
                messages = ((UIDFolder) folder).getMessagesByUID(uid + 1, UIDFolder.LASTUID);
                log.info("Archive has already seen this folder: " + descr
                        + " will only fetch messages from uid " + uid + " onwards, " + messages.length
                        + " messages will be incrementally fetched");
                haveUID = true;
            } else
                log.info(descr + " is a UIDFolder but not seen before");
        } else
            log.info(descr + " is not a UIDFolder");

        if (!haveUID) {
            log.info("All " + count + " messages in " + descr + " will be fetched");
            //messages = folder.getMessages();

            if (begin_msg_index > 0 && end_msg_index > 0) {
                // we have to use only specified messages
                // if there are 8 messages, count = 8, end_msg_index will be 9
                if (end_msg_index > count + 1)
                    log.warn("Warning: bad end_msg_index " + end_msg_index + " count = " + count); // use the full messages
                else {
                    int nMessages = end_msg_index - begin_msg_index;
                    Message[] newMessages = new Message[nMessages];
                    for (int i = 0; i < end_msg_index - begin_msg_index; i++)
                        newMessages[i] = folder.getMessage(begin_msg_index + i);//messages[begin_msg_index - 1 + i]; // -1 cos messages array is indexed from 0, but begin_msg_index from 1
                    log.info("total # of messages: " + count + " reduced # of messages: " + newMessages.length);
                    messages = newMessages;
                }
            }
        }
    }

    return messages;
}