Read latest email - JavaMail

-2

I have searched around here, but without success. Does anyone know how to fetch the most recent email using JavaMail ? What I'm using pulls all emails. My code:

        try {

            campolog.setContentType("text/html");

            Properties props = new Properties();

            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.starttls.enable", "true");
            Session emailSession = Session.getDefaultInstance(props);

            Store store = emailSession.getStore("imaps");
            store.connect("pop.gmail.com", "[email protected]", "senha");

//            javax.mail.Folder[] folders = store.getDefaultFolder().list("*");
//            for (javax.mail.Folder folder : folders) {
//                if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
//                    System.out.println(folder.getFullName() + ": " + folder.getMessageCount());
//                }
//            }

            Folder pastaEmail = store.getFolder("SMS");
            pastaEmail.open(Folder.READ_ONLY);

            Message[] mensagens = pastaEmail.getMessages();
            System.out.println("Total de Emails: " + mensagens.length);

            for (int i = 0, n = mensagens.length; i < n; i++) {
                    Message mensagem = mensagens[i];
                    //campolog.append("---------------------------------");
                    //campolog.append("Email Nº " + (i + 1));
                    //campolog.append("Assunto: " + mensagem.getSubject());
                    //campolog.setText("De: " + mensagem.getFrom()[0]);
                    campolog.setText("Mensagem: " + mensagem.getContent().toString());
            }

            pastaEmail.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
}
    
asked by anonymous 10.07.2018 / 03:24

1 answer

2

I have never used, but reading the API documentation:

I think you have to use getSortedMessages so you would sort by date, like this:

SortTerm[] termos = new SortTerm[1];

termos[0] = SortTerm.DATE; //Pode adicionar mais critérios de ordem adicionando termos[1], termos[2], etc

Folder pastaEmail = store.getFolder("SMS");
pastaEmail.open(Folder.READ_ONLY);

Message[] mensagens = ((IMAPFolder) pastaEmail).getSortedMessages(termos);
  

I followed the example of this SOen response: link

So to read the first message instead of for would just do a check like this:

if (mensagens.length > 0) {
    mensagens[0].getContent(); //Faça algo com o conteudo retornado
} else {
    //Não há mensagens
}

The SortTerm.DATE will sort by the date (and time) of sending the message, so you will pick up the time the sender sent, but if you need the time of "arrival", when your email box arrived, then use:

So:

SortTerm[] termos = new SortTerm[1];

termos[0] = SortTerm.ARRIVAL;

Folder pastaEmail = store.getFolder("SMS");
pastaEmail.open(Folder.READ_ONLY);

I have never used it, as I said, I only read the documentation and the answer, but I believe that this orders as expected, however if it is in reverse order, for example returning the oldest message in mensagens[0].getContent(); , then simply the last item of Message[] mensagens , like this:

if (mensagens.length > 0) {
    final int ultimaMensagem = mensagens.length - 1;
    mensagens[ultimaMensagem].getContent();
} else {
    //Não há mensagens
}

Or simply:

if (mensagens.length > 0) {
    mensagens[ mensagens.length - 1 ].getContent();
} else {
    //Não há mensagens
}
    
10.07.2018 / 03:43