Example usage for javax.mail Folder fetch

List of usage examples for javax.mail Folder fetch

Introduction

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

Prototype

public void fetch(Message[] msgs, FetchProfile fp) throws MessagingException 

Source Link

Document

Prefetch the items specified in the FetchProfile for the given Messages.

Usage

From source file:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java

@Test
public void testOpenImapConnection() throws Exception {
    Store mailAccount = null;/*from  w w w.  ja  v  a 2 s.co  m*/
    Folder inbox = null;
    Session mailSession = Session.getInstance(System.getProperties());
    try {
        mailSession.setDebug(true);
        mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol"));
        mailAccount.connect(props.getProperty("mail.server.host"),
                Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"),
                props.getProperty("mail.server.password"));
        inbox = mailAccount.getFolder("INBOX");
        if (inbox == null) {
            throw new MessagingException("No POP3 INBOX");
        }
        // -- Open the folder for read write --
        inbox.open(Folder.READ_WRITE);

        // -- Get the message wrappers and process them --
        javax.mail.Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
        MailProcessor processor = new MailProcessor();
        MessageListener mailingList = mock(MessageListener.class);
        when(mailingList.checkSender(anyString())).thenReturn(Boolean.TRUE);
        when(mailingList.getComponentId()).thenReturn("mailingList38");
        MessageEvent event = new MessageEvent();
        for (javax.mail.Message message : msgs) {
            processor.prepareMessage((MimeMessage) message, mailingList, event);
        }
        assertThat(event.getMessages(), is(notNullValue()));
        assertThat(event.getMessages().size(), is(msgs.length));
        for (com.silverpeas.mailinglist.service.model.beans.Message message : event.getMessages()) {
            assertThat(message, is(notNullValue()));
            assertThat(message.getMessageId(), is(notNullValue()));
        }
    } finally {
        // -- Close down nicely --
        if (inbox != null) {
            inbox.close(false);
        }
        if (mailAccount != null) {
            mailAccount.close();
        }
    }
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public long[] getMessageUIDs(Folder jxFolder, Message[] jxMessages) throws MailException {

    try {/* ww w . ja v a 2s . co  m*/
        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        long[] remoteMessageIds = new long[jxMessages.length];

        for (int i = 0; i < jxMessages.length; i++) {
            Message jxMessage = jxMessages[i];

            remoteMessageIds[i] = getUID(jxFolder, jxMessage);
        }

        return remoteMessageIds;
    } catch (MessagingException me) {
        throw new MailException(me);
    }
}

From source file:org.zilverline.core.IMAPCollection.java

private final boolean indexFolder(IndexWriter writer, Folder thisFolder) throws MessagingException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return false;
    }/*from   ww  w.  j  a  v a  2s  .  com*/
    if ((thisFolder.getType() & Folder.HOLDS_MESSAGES) != 0) {
        thisFolder.open(Folder.READ_ONLY);
        Message[] messages = thisFolder.getMessages(); // get refs to all msgs
        if (messages == null) {
            // dummy
            messages = new Message[0];
        }

        thisFolder.fetch(messages, PROFILE); // fetch headers

        log.debug("FOLDER: " + thisFolder.getFullName() + " messages=" + messages.length);

        for (int i = 0; i < messages.length; i++) {
            try {
                String msgID = null;
                if (messages[i] instanceof MimeMessage) {
                    MimeMessage mm = (MimeMessage) messages[i];
                    msgID = mm.getMessageID();
                }
                if (!md5DocumentCache.contains(msgID)) {
                    log.debug("new message added for message: " + msgID);
                    final Document doc = new Document();
                    doc.add(Field.Keyword(F_FOLDER, thisFolder.getFullName()));
                    doc.add(Field.Keyword("collection", name));
                    // index this message
                    indexMessage(doc, messages[i]);
                    // add it
                    writer.addDocument(doc);
                    md5DocumentCache.add(msgID);
                } else {
                    log.debug("existing message skipped for message: " + msgID);
                }
            } catch (Exception ioe) {
                // can be side effect of hosed up mail headers
                log.warn("Bad Message: " + messages[i], ioe);
                continue;
            }
        }

    }
    // recurse if possible
    if ((thisFolder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        Folder[] far = thisFolder.list();
        if (far != null) {
            for (int i = 0; i < far.length; i++) {
                indexFolder(writer, far[i]);
            }
        }
    }
    if (thisFolder.isOpen()) {
        log.debug("Closing folder: " + thisFolder.getFullName());
        thisFolder.close(false); // false => do not expunge
    }

    return true;
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void storeEnvelopes(long folderId, Folder jxFolder, Message[] jxMessages) throws PortalException {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();//from ww  w  . j  a  v  a2s.  co m

    try {
        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.ENVELOPE);
        fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS);
        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String sender = InternetAddressUtil.toString(jxMessage.getFrom());
            String to = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.TO));
            String cc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.CC));
            String bcc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.BCC));
            Date sentDate = jxMessage.getSentDate();
            String subject = jxMessage.getSubject();
            String flags = getFlags(jxMessage);
            long remoteMessageId = getUID(jxFolder, jxMessage);
            String contentType = jxMessage.getContentType();

            try {
                MessageLocalServiceUtil.getMessage(folderId, remoteMessageId);
            } catch (NoSuchMessageException nsme) {
                MessageLocalServiceUtil.addMessage(_user.getUserId(), folderId, sender, to, cc, bcc, sentDate,
                        subject, StringPool.BLANK, flags, remoteMessageId, contentType);
            }
        }

        com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId);

        FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(),
                jxFolder.getMessageCount());
    } catch (MessagingException me) {
        throw new MailException(me);
    }

    if (_log.isDebugEnabled()) {
        stopWatch.stop();

        _log.debug("Downloaded " + jxMessages.length + " messages from folder " + jxFolder.getFullName()
                + " completed in " + stopWatch.getTime() + " ms");
    }
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void storeContents(long folderId, long[] remoteMessageIds) throws IOException, PortalException {

    Folder jxFolder = null;

    try {/*from  w  w w .j av  a 2  s .  c  o m*/
        jxFolder = openFolder(folderId);

        Message[] jxMessages = getMessagesByUID(jxFolder, remoteMessageIds);

        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.CONTENT_INFO);
        fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS);
        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String flags = getFlags(jxMessage);

            long remoteMessageId = getUID(jxFolder, jxMessage);

            com.liferay.mail.model.Message message = MessageLocalServiceUtil.getMessage(folderId,
                    remoteMessageId);

            StringBundler bodyPlain = new StringBundler();
            StringBundler bodyHtml = new StringBundler();
            List<MailFile> mailFiles = new ArrayList<>();

            getParts(_user.getUserId(), bodyPlain, bodyHtml, StringPool.BLANK, jxMessage, mailFiles);

            if (bodyHtml.length() == 0) {
                if (bodyPlain.length() == 0) {
                    bodyHtml.append("&nbsp;");
                } else {
                    bodyHtml = bodyPlain;
                }
            }

            if (flags.indexOf(MailConstants.FLAG_SEEN) == -1) {
                jxMessage.setFlag(Flags.Flag.SEEN, false);
            }

            AttachmentLocalServiceUtil.deleteAttachments(message.getCompanyId(), message.getMessageId());

            for (MailFile mailFile : mailFiles) {
                AttachmentLocalServiceUtil.addAttachment(_user.getUserId(), message.getMessageId(),
                        mailFile.getContentPath(), mailFile.getFileName(), mailFile.getSize(),
                        mailFile.getFile());
            }

            MessageLocalServiceUtil.updateContent(message.getMessageId(), bodyHtml.toString(), flags);
        }
    } catch (MessagingException me) {
        throw new MailException(me);
    } finally {
        closeFolder(jxFolder, false);
    }
}

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

private List<EmailMessage> getEmailMessages(Folder mailFolder, int pageStart, int messageCount, Session session)
        throws MessagingException, IOException, ScanException, PolicyException {

    int totalMessageCount = mailFolder.getMessageCount();
    int start = Math.max(1, totalMessageCount - pageStart - (messageCount - 1));
    int end = Math.max(totalMessageCount - pageStart, 1);

    Message[] messages = totalMessageCount != 0 ? mailFolder.getMessages(start, end) : new Message[0];

    long startTime = System.currentTimeMillis();

    // Fetch only necessary headers for each message
    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.ENVELOPE);
    profile.add(FetchProfile.Item.FLAGS);
    profile.add(FetchProfile.Item.CONTENT_INFO);
    if (mailFolder instanceof UIDFolder) {
        profile.add(UIDFolder.FetchProfileItem.UID);
    }/*from  w w w. j a  va  2s  .  c o m*/
    mailFolder.fetch(messages, profile);

    if (log.isDebugEnabled()) {
        log.debug("Time elapsed while fetching message headers; {}ms", System.currentTimeMillis() - startTime);
    }

    List<EmailMessage> emails = new LinkedList<EmailMessage>();
    for (Message currentMessage : messages) {
        EmailMessage emailMessage = wrapMessage(currentMessage, false, session);
        emails.add(emailMessage);
    }

    Collections.reverse(emails);
    return emails;
}

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

private void readMessages(cfSession _Session, Folder popFolder, cfQueryResultData popData, int _start, int _max,
        boolean GetAll, File attachmentDir) throws cfmRunTimeException {
    try {/*  www .  j a v  a 2  s.c o  m*/
        int maxRows = _max;
        int startRow = _start;
        String messageNumber = getDynamic(_Session, "MESSAGENUMBER").getString();
        boolean containsUID = containsAttribute("UID");
        boolean usingMessageNumber = messageNumber.length() > 0;
        int msgCount = popFolder.getMessageCount();

        // if MAXROWS is not specified, or UID or MESSAGENUMBER is, then we want to get all the messages
        if (_max == -1 || containsUID || usingMessageNumber) {
            maxRows = msgCount;
        }
        if (containsUID || usingMessageNumber) {
            startRow = 1;
        }

        if (msgCount != 0 && startRow > msgCount) {
            throw newRunTimeException(
                    "The value of STARTROW must not be greater than the total number of messages in the folder, "
                            + popFolder.getMessageCount() + ".");
        }

        Message[] listOfMessages;
        if (!usingMessageNumber) {
            listOfMessages = popFolder.getMessages();
        } else {
            listOfMessages = popFolder.getMessages(getMessageList(messageNumber));
        }

        FetchProfile fProfile = new FetchProfile();
        fProfile.add(FetchProfile.Item.ENVELOPE);
        fProfile.add(UIDFolder.FetchProfileItem.UID);
        popFolder.fetch(listOfMessages, fProfile);

        if (containsUID) {
            String[] messageUIDList = getMessageUIDList(getDynamic(_Session, "UID").getString());

            for (int x = 0; x < listOfMessages.length; x++) {
                if (messageUIDList.length == 0
                        || messageUIDValid(messageUIDList, getMessageUID(popFolder, listOfMessages[x]))) {
                    populateMessage(_Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder);
                }
            }
        } else {
            popFolder.fetch(listOfMessages, fProfile);
            int end = startRow - 1 + maxRows;
            if (end > listOfMessages.length) {
                end = listOfMessages.length;
            }
            for (int x = startRow - 1; x < end; x++) {
                populateMessage(_Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder);
            }
        }
    } catch (Exception E) {
        if (E.getMessage() != null)
            throw newRunTimeException(E.getMessage());
        else
            throw newRunTimeException(E.toString());
    }

}

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  ww w .j a  v a 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   ww w. ja v  a2s  . com*/

    }

    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:net.wastl.webmail.server.WebMailSession.java

/**
 * Create a Message List.//from  w w  w.ja  v  a2 s . c o m
 * Fetches a list of headers in folder foldername for part list_part.
 * The messagelist will be stored in the "MESSAGES" environment.
 *
 * @param foldername folder for which a message list should be built
 * @param list_part part of list to display (1 = last xx messages, 2 = total-2*xx - total-xx messages)
 */
public void createMessageList(String folderhash, int list_part) throws NoSuchFolderException {
    long time_start = System.currentTimeMillis();
    TimeZone tz = TimeZone.getDefault();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
            user.getPreferredLocale());
    df.setTimeZone(tz);

    try {
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);
        Element xml_current = model.setCurrentFolder(folderhash);
        Element xml_messagelist = model.getMessageList(xml_folder);

        if (folder == null) {
            throw new NoSuchFolderException(folderhash);
        }

        long fetch_start = System.currentTimeMillis();

        if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        } else {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        }

        /* Calculate first and last message to show */
        int total_messages = folder.getMessageCount();
        int new_messages = folder.getNewMessageCount();
        int show_msgs = user.getMaxShowMessages();

        xml_messagelist.setAttribute("total", total_messages + "");
        xml_messagelist.setAttribute("new", new_messages + "");

        log.debug("Total: " + total_messages);

        /* Handle small messagelists correctly */
        if (total_messages < show_msgs) {
            show_msgs = total_messages;
        }
        /* Don't accept list-parts smaller than 1 */
        if (list_part < 1) {
            list_part = 1;
        }
        for (int k = 0; k < list_part; k++) {
            total_messages -= show_msgs;
        }
        /* Handle beginning of message list */
        if (total_messages < 0) {
            total_messages = 0;
        }
        int first = total_messages + 1;
        int last = total_messages + show_msgs;
        /* Set environment variable */
        setEnv();
        xml_current.setAttribute("first_msg", first + "");
        xml_current.setAttribute("last_msg", last + "");
        xml_current.setAttribute("list_part", list_part + "");

        /* Fetch headers */
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        log.debug("Last: " + last + ", first: " + first);
        Message[] msgs = folder.getMessages(first, last);
        log.debug(msgs.length + " messages fetching...");
        folder.fetch(msgs, fp);
        long fetch_stop = System.currentTimeMillis();

        Map header = new Hashtable(15);

        Flags.Flag[] sf;
        String from, to, cc, bcc, replyto, subject;
        String messageid;

        for (int i = msgs.length - 1; i >= 0; i--) {
            //              if(((MimeMessage)msgs[i]).getMessageID() == null) {
            //                  folder.close(false);
            //                  folder.open(Folder.READ_WRITE);
            //                  ((MimeMessage)msgs[i]).setHeader("Message-ID","<"+user.getLogin()+"."+System.currentTimeMillis()+".jwebmail@"+user.getDomain()+">");
            //                  ((MimeMessage)msgs[i]).saveChanges();
            //                  folder.close(false);
            //                  folder.open(Folder.READ_ONLY);
            //              }

            try {
                StringTokenizer tok = new StringTokenizer(((MimeMessage) msgs[i]).getMessageID(), "<>");
                messageid = tok.nextToken();
            } catch (NullPointerException ex) {
                // For mail servers that don't generate a Message-ID (Outlook et al)
                messageid = user.getLogin() + "." + i + ".jwebmail@" + user.getDomain();
            }

            XMLMessage xml_message = model.getMessage(xml_folder, msgs[i].getMessageNumber() + "", messageid);

            /* Addresses */
            from = "";
            replyto = "";
            to = "";
            cc = "";
            bcc = "";
            try {
                from = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getFrom()));
            } catch (UnsupportedEncodingException e) {
                from = Helper.joinAddress(msgs[i].getFrom());
            }
            try {
                replyto = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getReplyTo()));
            } catch (UnsupportedEncodingException e) {
                replyto = Helper.joinAddress(msgs[i].getReplyTo());
            }
            try {
                to = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO)));
            } catch (UnsupportedEncodingException e) {
                to = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO));
            }
            try {
                cc = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC)));
            } catch (UnsupportedEncodingException e) {
                cc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC));
            }
            try {
                bcc = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC)));
            } catch (UnsupportedEncodingException e) {
                bcc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC));
            }
            if (from == "")
                from = getStringResource("unknown sender");
            if (to == "")
                to = getStringResource("unknown recipient");

            /* Flags */
            sf = msgs[i].getFlags().getSystemFlags();
            String basepath = parent.getBasePath();

            for (int j = 0; j < sf.length; j++) {
                if (sf[j] == Flags.Flag.RECENT)
                    xml_message.setAttribute("recent", "true");
                if (sf[j] == Flags.Flag.SEEN)
                    xml_message.setAttribute("seen", "true");
                if (sf[j] == Flags.Flag.DELETED)
                    xml_message.setAttribute("deleted", "true");
                if (sf[j] == Flags.Flag.ANSWERED)
                    xml_message.setAttribute("answered", "true");
                if (sf[j] == Flags.Flag.DRAFT)
                    xml_message.setAttribute("draft", "true");
                if (sf[j] == Flags.Flag.FLAGGED)
                    xml_message.setAttribute("flagged", "true");
                if (sf[j] == Flags.Flag.USER)
                    xml_message.setAttribute("user", "true");
            }
            if (msgs[i] instanceof MimeMessage
                    && ((MimeMessage) msgs[i]).getContentType().toUpperCase().startsWith("MULTIPART/")) {
                xml_message.setAttribute("attachment", "true");
            }

            if (msgs[i] instanceof MimeMessage) {
                int size = ((MimeMessage) msgs[i]).getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");
            }

            /* Subject */
            subject = "";
            if (msgs[i].getSubject() != null) {
                try {
                    subject = MimeUtility.decodeText(msgs[i].getSubject());
                } catch (UnsupportedEncodingException ex) {
                    subject = msgs[i].getSubject();
                    log.warn("Unsupported Encoding: " + ex.getMessage());
                }
            }
            if (subject == null || subject.equals("")) {
                subject = getStringResource("no subject");
            }

            /* Set all of what we found into the DOM */
            xml_message.setHeader("FROM", from);
            try {
                // hmm, why decode subject twice? Though it doesn't matter..
                xml_message.setHeader("SUBJECT", MimeUtility.decodeText(subject));
            } catch (UnsupportedEncodingException e) {
                xml_message.setHeader("SUBJECT", subject);
                log.warn("Unsupported Encoding: " + e.getMessage());
            }
            xml_message.setHeader("TO", to);
            xml_message.setHeader("CC", cc);
            xml_message.setHeader("BCC", bcc);
            xml_message.setHeader("REPLY-TO", replyto);

            /* Date */
            Date d = msgs[i].getSentDate();
            String ds = "";
            if (d != null) {
                ds = df.format(d);
            }
            xml_message.setHeader("DATE", ds);
        }
        long time_stop = System.currentTimeMillis();
        // try {
        // XMLCommon.writeXML(model.getRoot(),new FileOutputStream("/tmp/wmdebug"),"");
        // } catch(IOException ex) {}

        log.debug("Construction of message list took " + (time_stop - time_start)
                + " ms. Time for IMAP transfer was " + (fetch_stop - fetch_start) + " ms.");
        folder.close(false);
    } catch (NullPointerException e) {
        log.error("Failed to construct message list", e);
        throw new NoSuchFolderException(folderhash);
    } catch (MessagingException ex) {
        log.error("Failed to construct message list.  " + "For some reason, contuing anyways.", ex);
    }
}