Filter reading emails from a date

1

I have the following code snippet that reads 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 reads all the emails that are in the inbox, is there any way to add a filter to read from a date?

    
asked by anonymous 19.05.2016 / 20:22

1 answer

1

I was able to solve the problem using javax.mail.search.SearchTerm and replacing inbox.getMessages() with inbox.search(dataInicio) as per 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

    
19.05.2016 / 21:35