Example usage for javax.mail.search FlagTerm FlagTerm

List of usage examples for javax.mail.search FlagTerm FlagTerm

Introduction

In this page you can find the example usage for javax.mail.search FlagTerm FlagTerm.

Prototype

public FlagTerm(Flags flags, boolean set) 

Source Link

Document

Constructor.

Usage

From source file:com.sonicle.webtop.mail.bol.model.ImapQuery.java

public static SearchTerm toSearchTerm(String allFlagStrings[], List<Tag> atags, QueryObj query,
        DateTimeZone timezone) {/*w w  w  .  j a va  2s . com*/
    SearchTerm searchTerm = null;
    ArrayList<SearchTerm> terms = new ArrayList<SearchTerm>();

    if (query != null) {
        ArrayList<Condition> conditionsList = query.conditions;
        String allText = query.allText;

        if (allText != null && allText.trim().length() > 0) {
            SearchTerm defaultterms[] = toDefaultSearchTerm(allText);
            terms.add(new OrTerm(defaultterms));
        }

        conditionsList.forEach(condition -> {
            String key = condition.keyword;
            String value = condition.value;

            if (key.equals(FROM)) {
                terms.add(new FromStringTerm(value));
            } else if (key.equals(TO)) {
                terms.add(new RecipientStringTerm(Message.RecipientType.TO, value));
            } else if (key.equals(SUBJECT)) {
                terms.add(new SubjectTerm(value));
            } else if (key.equals(MESSAGE)) {
                terms.add(new BodyTerm(value));
            } else if (key.equals(EVERYWHERE)) {
                SearchTerm anyterms[] = toAnySearchTerm(value);
                terms.add(new OrTerm(anyterms));
            } else if (key.equals(AFTER)) {
                Date afterDate = ImapQuery.parseDate(value, timezone);
                terms.add(new ReceivedDateTerm(DateTerm.GE, afterDate));
                terms.add(new SentDateTerm(DateTerm.GE, afterDate));
            } else if (key.equals(BEFORE)) {
                Date beforeDate = ImapQuery.parseDate(value, timezone);
                terms.add(new ReceivedDateTerm(DateTerm.LE, beforeDate));
                terms.add(new SentDateTerm(DateTerm.LE, beforeDate));

            } else if (value.equals(ATTACHMENT)) {

            } else if (value.equals(UNREAD)) {
                terms.add(new FlagTerm(new Flags(Flag.SEEN), false));
            } else if (value.equals(FLAGGED)) {
                FlagTerm fts[] = new FlagTerm[allFlagStrings.length + 1];
                fts[0] = new FlagTerm(new Flags(Flag.FLAGGED), true);
                for (int i = 0; i < allFlagStrings.length; ++i)
                    fts[i + 1] = new FlagTerm(new Flags(allFlagStrings[i]), true);
                terms.add(new OrTerm(fts));
            } else if (value.equals(TAGGED)) {
                FlagTerm fts[] = new FlagTerm[atags.size()];
                int i = 0;
                for (Tag tag : atags)
                    fts[i++] = new FlagTerm(new Flags(tag.getTagId()), true);
                terms.add(new OrTerm(fts));
            } else if (value.equals(UNANSWERED)) {
                terms.add(new FlagTerm(new Flags(Flag.ANSWERED), false));
            } else if (value.equals(PRIORITY)) {
                HeaderTerm p1 = new HeaderTerm("X-Priority", "1");
                HeaderTerm p2 = new HeaderTerm("X-Priority", "2");
                terms.add(new OrTerm(p1, p2));
            }

        });
    }

    int n = terms.size();
    if (n == 1) {
        searchTerm = terms.get(0);
    } else if (n > 1) {
        SearchTerm vterms[] = new SearchTerm[n];
        terms.toArray(vterms);
        searchTerm = new AndTerm(vterms);
    }
    return searchTerm;
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

public synchronized static Message[] readAll(String protocol, String server, int securityConnection, int port,
        String user, String password, boolean onlyUnreadMessages) {
    Message[] msgs = null;/*w w  w .j ava 2  s . c  om*/
    try {
        Properties props = System.getProperties();
        updateSecurityProps(protocol, server, securityConnection, props);
        Session session = Session.getDefaultInstance(props, null);

        if (LOGGER.isDebugEnabled()) {
            session.setDebug(true);
        } else {
            session.setDebug(false);
        }

        // instantiate POP3-store and connect to server
        store = session.getStore(protocol);
        boolean connected = SyncStore.connect(store, protocol, server, port, user, password);
        if (!connected) {
            return msgs;
        }
        connPoint = SyncStore.getConnPoint(store, protocol, server, port, user, password);
        store = connPoint.getStore();

        // access default folder
        folder = store.getDefaultFolder();

        // can't find default folder
        if (folder == null) {
            throw new Exception("No default folder");
        }

        // messages are always in folder INBOX
        folder = folder.getFolder("INBOX");

        // can't find INBOX
        if (folder == null) {
            throw new Exception("No POP3 INBOX");
        }

        // open folder
        folder.open(Folder.READ_WRITE);

        // retrieve messages
        if (onlyUnreadMessages) {
            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            msgs = folder.search(ft);
        } else {
            msgs = folder.getMessages();
        }
    } catch (Exception ex) {
        if (LogThrottle.isReady("MailReader1", 240)) {
            LOGGER.error(ExceptionUtils.getStackTrace(ex));
        }
    }
    return msgs;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public int numCorreosNOL(String name) {
    int numMensa = 0;
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {//from w w w  . j a va2s  . c om
        users u = usuarioService.getByLogin(name);

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

        Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        System.out.println(" " + msg.length);
        numMensa = msg.length;
    } catch (Exception ex) {
    }
    return numMensa;
}

From source file:gmailclientfx.controllers.SpamController.java

public void fetchSpam() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacFrom.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    spamTable.setItems(data);//from  w w  w. j a  va  2  s .  c  om
    spamTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = spamTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                    stage.show();
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });
    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);
        Folder spam = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Junk".equals(att)) {
                    spam = f;
                }
            }
        }
        spam.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) spam
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "SPAM");
            data.add(msg);
        }
        MimeMessage[] unseenMessages = (MimeMessage[]) spam
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "SPAM");
            data.add(msg);
        }
        spam.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(SpamController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.robin.utilities.Utilities.java

/**
 * A utility that waits for a gmail mailbox to receive a new message with
 * according to a given SearchTerm. Only "Not seen" messages are searched,
 * and all match is set as SEEN, but just the first occurrence of the
 * matching message is returned./*from   w  w w.j av a  2 s  .c  o m*/
 * @param username the mailbox owner's user name (no @gmail.com required).
 * @param pass the user password protecting this mailbox
 * @param st the SearchTerm built to filter messages
 * @param timeoutMessage the message to show when no such mail found within
 *            timeout
 * @param timeout The maximum amount of time to wait in milliseconds.
 * @return a last from the new messages thats match the st conditions
 */
public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st,
        final String timeoutMessage, final long timeout) {
    String host = "imap.gmail.com";
    final long retryTime = 1000;

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.put("mail.imaps.ssl.trust", "*");
    EMail email = null;
    Session session = Session.getDefaultInstance(props, null);
    try {
        Store store = session.getStore("imaps");
        store.connect(host, username, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox)
                .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS)
                .withMessage(timeoutMessage);
        email = waitForMail.until(new Function<Folder, EMail>() {
            @Override
            public EMail apply(final Folder inbox) {
                EMail email = null;
                FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
                SearchTerm sst = new AndTerm(ft, st);
                try {
                    inbox.getMessageCount();
                    Message[] messages = inbox.search(sst);
                    for (Message message : messages) {
                        message.setFlag(Flag.SEEN, true);
                    }
                    if (messages.length > 0) {
                        return new EMail(messages[0]);
                    }
                } catch (MessagingException e) {
                    Assert.fail(e.getMessage());
                }
                return email;
            }
        });
        inbox.close(false);
        store.close();
    } catch (MessagingException e) {
        Assert.fail(e.getMessage());
    }
    return email;
}

From source file:gmailclientfx.controllers.PoslaneController.java

public void fetchPoslane() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacTo.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    poslaneTable.setItems(data);/*w w  w.  j a v  a 2 s  .  c o m*/
    poslaneTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = poslaneTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                    stage.show();
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });
    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);

        Folder poslane = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Sent".equals(att)) {
                    poslane = f;
                }
            }
        }
        poslane.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) poslane
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "SENT");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) poslane
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "SENT");
            data.add(msg);
        }
        poslane.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(PoslaneController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:gmailclientfx.controllers.ObrisaneController.java

public void fetchObrisane() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacFrom.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    obrisaneTable.setItems(data);// w  w  w  .  j  a  v a 2  s. c o  m
    obrisaneTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = obrisaneTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.show();
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });
    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);

        Folder obrisane = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Trash".equals(att)) {
                    obrisane = f;
                }
            }
        }
        obrisane.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) obrisane
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "DELETED");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) obrisane
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "DELETED");
            data.add(msg);
        }
        obrisane.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(ObrisaneController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:gmailclientfx.controllers.NedovrseneController.java

public void fetchNedovrsene() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacTo.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    nedovrseneTable.setItems(data);//from  w  ww .  jav  a  2  s  . c  om
    nedovrseneTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = nedovrseneTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                    stage.show();
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });

    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);

        Folder nedovrsene = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Drafts".equals(att)) {
                    nedovrsene = f;
                }
            }
        }
        nedovrsene.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) nedovrsene
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "DRAFT");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) nedovrsene
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "DRAFT");
            data.add(msg);
        }
        nedovrsene.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(NedovrseneController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:gmailclientfx.controllers.InboxController.java

public void fetchInbox() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacPosiljatelj.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    Platform.runLater(() -> {/*from   ww  w  .j a v a  2 s .  c o  m*/
        inboxTable.setItems(data);
    });
    inboxTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = inboxTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                    stage.show();
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });

    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);
        int getSeenCount = inbox.getMessageCount();
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfileItem.FLAGS);
        fp.add(FetchProfileItem.CONTENT_INFO);
        fp.add("X-mailer");

        MimeMessage[] seenMessages = (MimeMessage[]) inbox
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "INBOX");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) inbox
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "INBOX");
            data.add(msg);
        }

        inbox.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

@Override
public GmailMessageList getMessagesBy(EmailSearchStrategy strategy, String value) {
    SearchTerm seekStrategy = null;/*from   www .  j  av a 2 s  .  c o  m*/
    switch (strategy) {
    case SUBJECT:
        seekStrategy = new SubjectTerm(value);
        LOG.debug("Fetching emails with a subject of \"" + value + "\"");
        break;
    case TO:
        seekStrategy = new RecipientStringTerm(Message.RecipientType.TO, value);
        LOG.debug("Fetching emails sent to \"" + value + "\"");
        break;
    case FROM:
        seekStrategy = new FromStringTerm(value);
        LOG.debug("Fetching emails sent from \"" + value + "\"");
        break;
    case CC:
        seekStrategy = new RecipientStringTerm(Message.RecipientType.CC, value);
        LOG.debug("Fetching emails CC'd to \"" + value + "\"");
        break;
    case DATE_GT:
        seekStrategy = new SentDateTerm(SentDateTerm.GT, parseDate(value));
        LOG.debug("Fetching emails with a send date newer than \"" + value + "\"");
        break;
    case DATE_LT:
        seekStrategy = new SentDateTerm(SentDateTerm.LT, parseDate(value));
        LOG.debug("Fetching emails with a send date newer than \"" + value + "\"");
        break;
    case DATE_EQ:
        seekStrategy = new SentDateTerm(SentDateTerm.EQ, parseDate(value));
        LOG.debug("Fetching emails with a send date newer than \"" + value + "\"");
        break;
    case KEYWORD:
        seekStrategy = new BodyTerm(value);
        LOG.debug("Fetching emails containing the keyword \"" + value + "\"");
        break;
    case UNREAD:
        seekStrategy = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        LOG.debug("Fetching all unread emails");
        break;
    }
    try {
        final GmailMessageList found = new GmailMessageList();
        final Store store = openGmailStore();
        final Folder folder = getFolder(this.srcFolder, store);
        folder.open(Folder.READ_ONLY);
        for (final Message msg : folder.search(seekStrategy)) {
            found.add(new JavaMailGmailMessage(msg));
        }
        LOG.debug("Found " + found.size() + " emails");
        return found;
    } catch (final Exception e) {
        throw new GmailException("Failed getting unread messages", e);
    }
}