Example usage for javax.mail Folder getMessages

List of usage examples for javax.mail Folder getMessages

Introduction

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

Prototype

public synchronized Message[] getMessages(int start, int end) throws MessagingException 

Source Link

Document

Get the Message objects for message numbers ranging from start through end, both start and end inclusive.

Usage

From source file:copier.java

public static void main(String argv[]) {
    boolean debug = false; // change to get more errors

    if (argv.length != 5) {
        System.out.println("usage: copier <urlname> <src folder>" + "<dest folder> <start msg #> <end msg #>");
        return;/*from   w  w w  .  j ava 2  s .  c o m*/
    }

    try {
        URLName url = new URLName(argv[0]);
        String src = argv[1]; // source folder
        String dest = argv[2]; // dest folder
        int start = Integer.parseInt(argv[3]); // copy from message #
        int end = Integer.parseInt(argv[4]); // to message #

        // Get the default Session object

        Session session = Session.getInstance(System.getProperties(), null);
        // session.setDebug(debug);

        // Get a Store object that implements the protocol.
        Store store = session.getStore(url);
        store.connect();
        System.out.println("Connected...");

        // Open Source Folder
        Folder folder = store.getFolder(src);
        folder.open(Folder.READ_WRITE);
        System.out.println("Opened source...");

        if (folder.getMessageCount() == 0) {
            System.out.println("Source folder has no messages ..");
            folder.close(false);
            store.close();
        }

        // Open destination folder, create if needed 
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists()) // create
            dfolder.create(Folder.HOLDS_MESSAGES);

        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Got messages...");

        // Copy messages into destination, 
        folder.copyMessages(msgs, dfolder);
        System.out.println("Copied messages...");

        // Close the folder and store
        folder.close(false);
        store.close();
        System.out.println("Closed folder and store...");

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

    System.exit(0);
}

From source file:MainClass.java

public static void main(String argv[]) {
    boolean debug = false;// change to get more errors

    if (argv.length != 5) {
        System.out.println("usage: copier <urlname> <src folder>" + "<dest folder> <start msg #> <end msg #>");
        return;//from   ww w  .  j  av  a  2s.  com
    }

    try {
        URLName url = new URLName(argv[0]);
        String src = argv[1]; // source folder
        String dest = argv[2]; // dest folder
        int start = Integer.parseInt(argv[3]); // copy from message #
        int end = Integer.parseInt(argv[4]); // to message #

        // Get the default Session object

        Session session = Session.getInstance(System.getProperties(), null);
        // session.setDebug(debug);

        // Get a Store object that implements
        // the protocol.
        Store store = session.getStore(url);
        store.connect();
        System.out.println("Connected...");

        // Open Source Folder
        Folder folder = store.getFolder(src);
        folder.open(Folder.READ_WRITE);
        System.out.println("Opened source...");

        if (folder.getMessageCount() == 0) {
            System.out.println("Source folder has no messages ..");
            folder.close(false);
            store.close();
        }

        // Open destination folder, create if needed
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists()) // create
            dfolder.create(Folder.HOLDS_MESSAGES);

        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Got messages...");

        // Copy messages into destination,
        folder.copyMessages(msgs, dfolder);
        System.out.println("Copied messages...");

        // Close the folder and store
        folder.close(false);
        store.close();
        System.out.println("Closed folder and store...");

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

    System.exit(0);
}

From source file:mover.java

public static void main(String argv[]) {
    int start = 1;
    int end = -1;
    int optind;//www  .jav  a 2  s.c  o  m

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) { // protocol
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) { // host
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) { // user
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) { // password
            password = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-s")) { // Source mbox
            src = argv[++optind];
        } else if (argv[optind].equals("-d")) { // Destination mbox
            dest = argv[++optind];
        } else if (argv[optind].equals("-x")) { // Expunge ?
            expunge = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: mover [-T protocol] [-H host] [-U user] [-P password] [-L url] [-v]");
            System.out.println("\t[-s source mbox] [-d destination mbox] [-x] [msgnum1] [msgnum2]");
            System.out.println("\t The -x option => EXPUNGE deleted messages");
            System.out.println("\t msgnum1 => start of message-range; msgnum2 => end of message-range");
            System.exit(1);
        } else {
            break;
        }
    }

    if (optind < argv.length)
        start = Integer.parseInt(argv[optind++]); // start msg

    if (optind < argv.length)
        end = Integer.parseInt(argv[optind++]); // end msg

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

        // Get a Session object
        Session session = Session.getInstance(props, 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();
        }

        // Open source Folder
        Folder folder = store.getFolder(src);
        if (folder == null || !folder.exists()) {
            System.out.println("Invalid folder: " + src);
            System.exit(1);
        }

        folder.open(Folder.READ_WRITE);

        int count = folder.getMessageCount();
        if (count == 0) { // No messages in the source folder
            System.out.println(folder.getName() + " is empty");
            // Close folder, store and return
            folder.close(false);
            store.close();
            return;
        }

        // Open destination folder, create if reqd
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists())
            dfolder.create(Folder.HOLDS_MESSAGES);

        if (end == -1)
            end = count;

        // Get the message objects to copy
        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Moving " + msgs.length + " messages");

        if (msgs.length != 0) {
            folder.copyMessages(msgs, dfolder);
            folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);

            // Dump out the Flags of the moved messages, to insure that
            // all got deleted
            for (int i = 0; i < msgs.length; i++) {
                if (!msgs[i].isSet(Flags.Flag.DELETED))
                    System.out.println("Message # " + msgs[i] + " not deleted");
            }
        }

        // Close folders and store
        folder.close(expunge);
        store.close();

    } catch (MessagingException mex) {
        Exception ex = mex;
        do {
            System.out.println(ex.getMessage());
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:MainClass.java

public static void main(String argv[]) {
    int start = 1;
    int end = -1;
    int optind;//from w  w  w .j av a 2s.  co m

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) { // protocol
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) { // host
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) { // user
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) { // password
            password = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-s")) { // Source mbox
            src = argv[++optind];
        } else if (argv[optind].equals("-d")) { // Destination mbox
            dest = argv[++optind];
        } else if (argv[optind].equals("-x")) { // Expunge ?
            expunge = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: mover [-T protocol] [-H host] [-U user] [-P password] [-L url] [-v]");
            System.out.println("\t[-s source mbox] [-d destination mbox] [-x] [msgnum1] [msgnum2]");
            System.out.println("\t The -x option => EXPUNGE deleted messages");
            System.out.println("\t msgnum1 => start of message-range; msgnum2 => end of message-range");
            System.exit(1);
        } else {
            break;
        }
    }

    if (optind < argv.length)
        start = Integer.parseInt(argv[optind++]); // start msg

    if (optind < argv.length)
        end = Integer.parseInt(argv[optind++]); // end msg

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

        // Get a Session object
        Session session = Session.getInstance(props, 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();
        }

        // Open source Folder
        Folder folder = store.getFolder(src);
        if (folder == null || !folder.exists()) {
            System.out.println("Invalid folder: " + folder.getName());
            System.exit(1);
        }

        folder.open(Folder.READ_WRITE);

        int count = folder.getMessageCount();
        if (count == 0) { // No messages in the source folder
            System.out.println(folder.getName() + " is empty");
            // Close folder, store and return
            folder.close(false);
            store.close();
            return;
        }

        // Open destination folder, create if reqd
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists())
            dfolder.create(Folder.HOLDS_MESSAGES);

        if (end == -1)
            end = count;

        // Get the message objects to copy
        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Moving " + msgs.length + " messages");

        if (msgs.length != 0) {
            folder.copyMessages(msgs, dfolder);
            folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);

            // Dump out the Flags of the moved messages, to insure that
            // all got deleted
            for (int i = 0; i < msgs.length; i++) {
                if (!msgs[i].isSet(Flags.Flag.DELETED))
                    System.out.println("Message # " + msgs[i] + " not deleted");
            }
        }

        // Close folders and store
        folder.close(expunge);
        store.close();

    } catch (MessagingException mex) {
        Exception ex = mex;
        do {
            System.out.println(ex.getMessage());
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

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

private void readMessagesFolder(Folder folder) throws MessagingException, IOException, SearchLibException {
    folder.open(Folder.READ_ONLY);/*from ww  w.  j  a va 2 s .c  om*/
    String folderFullName = folder.getFullName();
    try {
        int max = folder.getMessageCount();
        int i = 0;
        final int buffer = item.getBufferSize();
        while (i < max && !thread.isAborted()) {
            thread.setStatusInfo(CrawlStatus.CRAWL);
            int end = i + buffer;
            if (end > max)
                end = max;
            Message[] messages = folder.getMessages(i + 1, end);
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            folder.fetch(messages, fp);
            for (Message message : messages) {
                if (thread.isAborted())
                    break;
                i++;
                String messageId = getMessageId(folder, message);
                if (StringUtils.isEmpty(messageId))
                    continue;
                if (thread.isAlreadyIndexed(messageId)) {
                    thread.incIgnored();
                    continue;
                }
                IndexDocument crawlIndexDocument = new IndexDocument(item.getLang());
                IndexDocument parserIndexDocument = new IndexDocument(item.getLang());
                crawlIndexDocument.addString(MailboxFieldEnum.folder.name(), folderFullName);
                try {
                    readMessage(crawlIndexDocument, parserIndexDocument, folder, message, messageId);
                    thread.addDocument(crawlIndexDocument, parserIndexDocument);
                } catch (Exception e) {
                    Logging.warn(e);
                    thread.incError();
                }
            }
        }
    } finally {
        folder.close(false);
    }
}

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

private ProcessResult processMessageSlice(final int start, final int end, final String folderName)
        throws Exception {

    logger.debug("processMessageSlice() started with " + start + "/" + end + "/" + folderName);
    final long startTime = System.currentTimeMillis();
    final Store store = Session.getInstance(props).getStore();
    store.connect(user, password);//from   w  w  w . j  a va  2  s. c  o m
    final Folder folder = store.getFolder(folderName);
    final UIDFolder uidfolder = (UIDFolder) folder;

    IMAPUtils.open(folder);

    try {

        final Message[] msgs = folder.getMessages(start, end);
        folder.fetch(msgs, IMAPUtils.FETCH_PROFILE_HEAD);

        logger.debug("folder fetch done");

        long highestUid = 0;
        int processedCount = 0;

        for (final Message m : msgs) {
            try {

                IMAPUtils.open(folder);
                final long uid = uidfolder.getUID(m);

                mailDestination.onMessage(m);

                highestUid = Math.max(highestUid, uid);
                processedCount++;

                if (Thread.currentThread().isInterrupted()) {
                    break;
                }

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

                IMAPUtils.open(folder);
            }
        }

        final long endTime = System.currentTimeMillis() + 1;
        final ProcessResult pr = new ProcessResult(highestUid, processedCount, endTime - startTime);
        logger.debug("processMessageSlice() ended with " + pr);
        return pr;

    } finally {

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

}

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  av  a  2  s  .co  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.liferay.mail.imap.IMAPAccessor.java

public long[] getMessageUIDs(long folderId, int pageNumber, int messagesPerPage) throws PortalException {

    Folder jxFolder = null;

    try {//from  w  w  w  .  java 2s  .c  o  m
        jxFolder = openFolder(folderId);

        int[] messageIndexes = getMessageIndexes(jxFolder.getMessageCount(), pageNumber, messagesPerPage);

        if (messageIndexes[0] == 0) {
            return new long[0];
        }

        Message[] jxMessages = jxFolder.getMessages(messageIndexes[0], messageIndexes[1]);

        return getMessageUIDs(jxFolder, jxMessages);
    } catch (MessagingException me) {
        throw new MailException(me);
    } finally {
        closeFolder(jxFolder, false);
    }
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

/**
 * {@inheritDoc}/*from  ww w  . j  a  va 2  s  .com*/
 */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    boolean isOK = false; // Did sample succeed?
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();

    parent.setSampleLabel(getName());

    String samplerString = toString();
    parent.setSamplerData(samplerString);

    /*
     * Perform the sampling
     */
    parent.sampleStart(); // Start timing
    try {
        // Create empty properties
        Properties props = new Properties();

        if (isUseStartTLS()) {
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$
            }
        }

        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: "
                        + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  "
                        + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: "
                            + truststore.getAbsolutePath()
                            + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : "
                            + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ 
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        }

        // Get session
        Session session = Session.getInstance(props, null);

        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());

        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }

        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        parent.setContentType("text/plain"); // $NON-NLS-1$

        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();

            cdata.append("Message "); // $NON-NLS-1$
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);

            final String contentType = message.getContentType();
            child.setContentType(contentType);// Store the content-type
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default
            child.setEncodingAndType(contentType);// Parse the content-type

            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                child.setResponseData(bout.toByteArray()); // Save raw message
                child.setDataType(SampleResult.TEXT);
            } else {
                @SuppressWarnings("unchecked") // Javadoc for the API says this is OK
                Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                        // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }

            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }

        // Close connection
        folder.close(true);
        store.close();

        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$
    } finally {
        busy = false;
    }

    if (parent.getEndTime() == 0) {// not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}

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

/**
 * Create a Message List./* www. j  a v a2s .c om*/
 * 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);
    }
}