Example usage for javax.mail Folder getMessageCount

List of usage examples for javax.mail Folder getMessageCount

Introduction

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

Prototype

public abstract int getMessageCount() throws MessagingException;

Source Link

Document

Get total number of messages in this Folder.

Usage

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;/*from w  w w.j  a  v a2s. com*/
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        if (!dst.create(src.getType())) {
            // might not be able to create a folder that holds both
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                // might only be able to create one type (Gmail)
                if (!dst.create(Folder.HOLDS_MESSAGES)) {
                    System.out.println("couldn't create " + dst.getFullName());
                    return;
                }
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

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);/* w  w w .  j a  v a  2  s. c o m*/
    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:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java

@Override
public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
        Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(),
                "Enter Gmail Credentials", getGmailUsername(), getGmailPassword());
        if (credentials == null)
            return null;
        setGmailUsername(credentials.first());
        setGmailPassword(credentials.second());
        PluginUtils.saveProperties("conf/rockblock.props", this);
        askGmailPassword = false;//from  w w  w  . ja  va 2s. c  o m
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        int numMsgs = inbox.getMessageCount();

        for (int i = numMsgs; i > 0; i--) {
            Message m = inbox.getMessage(i);
            if (m.getReceivedDate().before(timeSince)) {
                break;
            } else {
                MimeMultipart mime = (MimeMultipart) m.getContent();
                for (int j = 0; j < mime.getCount(); j++) {
                    BodyPart p = mime.getBodyPart(j);
                    Matcher matcher = pattern.matcher(p.getContentType());
                    if (matcher.matches()) {
                        InputStream stream = (InputStream) p.getContent();
                        byte[] data = IOUtils.toByteArray(stream);
                        IridiumMessage msg = process(data, matcher.group(1));
                        if (msg != null)
                            messages.add(msg);
                    }
                }
            }
        }
    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (MessagingException ex) {
        ex.printStackTrace();
        System.exit(2);
    }

    return messages;
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start,
        final int deleteCount, final String user, final String password) throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);//from   w  ww  .  java 2  s  .  co  m
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m = deleteCount == -1 ? f.getMessages()
            : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
        message.setFlag(Flag.DELETED, true);
        logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
        d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();

}

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;/*from   w  w w  .ja  va  2  s . co  m*/
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        try {
            if (!dst.create(src.getType())) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
        } catch (MessagingException mex) {
            // might not be able to create a folder that holds both
            if (src.getType() != (Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS))
                throw mex;
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

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

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

    assert (getMailSource() != null);

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

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

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

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

    store.close();

    return folderItems;

}

From source file:org.apache.hupa.server.handler.FetchFoldersHandler.java

/**
 * Create a new IMAPFolder from the given Folder
 * // w w w  . j  ava 2 s  .  com
 * @param folder Current folder
 * @return imapFolder Created IMAPFolder
 * @throws ActionException If an error occurs
 * @throws MessagingException If an error occurs
 */
private IMAPFolder createIMAPFolder(Folder folder) throws ActionException {

    String fullName = folder.getFullName();
    String delimiter;
    IMAPFolder iFolder = null;

    try {
        logger.debug("Creating folder: " + fullName + " for user: " + getUser());
        delimiter = String.valueOf(folder.getSeparator());
        iFolder = new IMAPFolder(fullName);
        iFolder.setDelimiter(delimiter);
        if ("[Gmail]".equals(folder.getFullName()))
            return iFolder;
        iFolder.setMessageCount(folder.getMessageCount());
        iFolder.setSubscribed(folder.isSubscribed());
        iFolder.setUnseenMessageCount(folder.getUnreadMessageCount());
    } catch (MessagingException e) {
        logger.error("Unable to construct folder " + folder.getFullName(), e);
    }

    return iFolder;
}

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

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

From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java

public Message[] getPOPMessages(Folder folder, int retrievemails) throws Exception {
    // Get  messages ..
    try {//from  w  w  w  . j  a  v  a2 s  . c  om
        int newMsgs = folder.getNewMessageCount();
        int msgCount = folder.getMessageCount();
        Message msgsAll[] = folder.getMessages();

        if (retrievemails == 1) {
            Message msgsNew[] = folder.getMessages(msgCount - newMsgs + 1, msgCount);
            return (msgsNew);

        } else {
            return (msgsAll);
        }
    }

    catch (Exception e) {
        return null;
    }

}

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

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

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

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

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

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

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

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

    store.close();

    return folderItems;

}