Filter reading emails from a date

I have the following snippet of code that performs the reading of emails from the inbox.

try {
    email.conectar();
    javax.mail.Store store = email.getArquivoEmail();
    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_ONLY);

    //Aqui gostaria de pegar apenas e-mails dos Ășltimos 10 dias.
    for ( Message message : inbox.getMessages() ){
        System.out.println("Mensagem: " + message.getSubject());
        System.out.println("Data: " + ElfabDateUtils.formatDateOnly(message.getReceivedDate()));
    }

} catch (MessagingException ex) {
    logger.log(Level.SEVERE, null, ex);
}

But this code does the reading of all the emails that are in the Inbox, is there any way to add a filter so that the reading is done from a date?

Author: Elyel Rubens da Rosa, 2016-05-19

1 answers

I managed to solve the problem used javax.mail.search.SearchTerm and replacing inbox.getMessages() with inbox.search(dataInicio) as code below.

    try {
        email.conectar();
        javax.mail.Store store = email.getArquivoEmail();
        Folder inbox = store.getFolder("inbox");
        inbox.open(Folder.READ_ONLY);
        SearchTerm dataInicio = new ReceivedDateTerm(ComparisonTerm.GT, ElfabDateUtils.alterarDias(new Date(), -10));

        for ( Message message : inbox.search(dataInicio) ){
            System.out.println("Mensagem: " + message.getSubject());
            System.out.println("Data: " + message.getReceivedDate());
        }

    } catch (MessagingException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

Reference: Link SO.com

 1
Author: Elyel Rubens da Rosa, 2017-05-23 12:37:27