Read latest email - Javamail

Asked

Viewed 702 times

-2

I gave a search here but unsuccessfully. Someone knows how to find the latest email using the JavaMail? What I’m using pulls all the 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();
        }
}
  • Then in that case I would need to have the exact "position" of the email. Example: Email1, Email2....

1 answer

2


Never used, but reading the API documentation:

I guess you have to use getSortedMessages then you would order by date, so:

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);

The code I did following the example of this reply from Soen: https://stackoverflow.com/a/50994431/1518921

So to read the first message instead of the for I’d 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 by the time the sender sent, but if you need the time of "arrival", when it arrived to your email box, then use:

Thus:

SortTerm[] termos = new SortTerm[1];

termos[0] = SortTerm.ARRIVAL;

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

I have never used, as I said, only read the documentation and the reply, but I believe that this sort as expected, however if it is in reverse order, for example return the oldest message on mensagens[0].getContent(); then just reverse by taking the last item of Message[] mensagens, thus:

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
}
  • It worked! Thank you very much! I took the opportunity to search the documentation as I treated the email, removing some parts. I couldn’t find anything on. You don’t have to give me the answer, but did you see any of that there? Or you can give me tips on how to search?

  • @Abnerrodrigues depends on what you want to remove from the email to be displayed, if you can say I read the doc better and try to put as an example ;)

  • Look, I get the email like this: Mensagem: *** EMAIL AUTOMATICO, POR FAVOR NAO RESPONDA *** Ola abnerodrigs Voce recebeu uma resposta. Numero do Celular: 11982743910 SMS que voce enviou: Ola, o visitante: Fulanochegou! Podemos autorizar a entrada? Digite 1 para sim ou 2 para nao. Mensagem Respondida pelo Celular: 1 I wanted to leave only the part "Answered by Cellular: 1"

  • @Abnerrodrigues this part will have to use regex, can create a new question explaining that wants to extract from a string this part, then I will formulate a new answer, not to mix the subjects. Please mark this answer as correct, thank you! If you do not know how to read this link: https://pt.meta.stackoverflow.com/q/1078/3635

  • Thank you for!!

  • @Abnerrodrigues as soon as I ask the question, copy the link and send me here to answer :)

  • Vixi, it won’t happen. I’ve reached the limit of questions (One a day is dirty) and I’ll need to wait longer 6 days to ask again... But thank you so much, I will try to give a search here. Thank you very much!!

  • @Abnerrodrigues I’ll send you the code, I just need to test it and I’ll send it to you

  • Oops, thank you very much!!!

  • @Abnerrodrigues ready, I made an example for you to study how to take the part of the string needed: https://repl.it/@inphinit/Extract-phone-regexjava

  • 2

    Thank you very much man, I love you! Hahahaha. EVEN WORTH <3

Show 6 more comments

Browser other questions tagged

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