Filter email reading from a date

Asked

Viewed 106 times

1

I have the following piece 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);
}

However this code reads all the emails that are in the inbox, there is some way to add a filter so that the reading is done from a date?

1 answer

1


I was able to solve the problem used javax.mail.search.SearchTerm and replacing inbox.getMessages() for 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.