How to read emails sent from gmail using javamail?

1

I have a problem in which I have to read the emails that I have sent. That part I do, but only those that I sent by javamail and do not read all those that I have sent, just read me one.

Properties p = new Properties();

p.setProperty("mail.store.protocol", "imaps");

Session sesion = Session.getInstance(p);

sesion.setDebug(true);

Store store = sesion.getStore();

store.connect("imap.gmail.com", "[email protected]", "miclavedegmail");

Folder folder = store.getFolder("[Gmail]/Enviados");

folder.open(Folder.READ_ONLY);

mensajes = folder.getMessages();

Message m = folder.getMessage(folder.getMessageCount());

Address[] in = m.getFrom();

for (Address address : in) {
      System.out.println("Email: "+address.toString()+"\n");
}

Multipart mp = (Multipart) m.getContent();

BodyPart bp = mp.getBodyPart(0);

System.out.println("Bcc User Name: "+InternetAddress.toString(m.getRecipients(Message.RecipientType.BCC)));
System.out.println("SENT DATE: "+m.getSentDate());
System.out.println("SUBJECT: "+m.getSubject());
System.out.println("Content: "+bp.getContent());

There he is entering my mail box but as I said, he only reads a single email.

    
asked by Jhonny Luis 29.03.2017 в 23:51
source

1 answer

2

You should loop through the messages obtained:

mensajes = folder.getMessages();

for (Message m : mensajes) {

    Address[] in = m.getFrom();

    for (Address address : in) {
        System.out.println("Email: "+address.toString()+"\n");
    }

    Multipart mp = (Multipart) m.getContent();

    BodyPart bp = mp.getBodyPart(0);

    System.out.println("Bcc User Name: "+InternetAddress.toString(m.getRecipients(Message.RecipientType.BCC)));
    System.out.println("SENT DATE: "+m.getSentDate());
    System.out.println("SUBJECT: "+m.getSubject());
    System.out.println("Content: "+bp.getContent());

}

That if you get them all at once and then process them. You could also get each one and process it:

for(int i = 0; i < folder.getMessageCount(); i++) {
    Message m = folder.getMessage(i);

    // Procesar el mensaje.
}

If you look at the documentation for getMessages () , this returns an array with all the messages. Hence, you have to go through it to show them. And as you know how many they are, the best structure to go through is a for loop.

    
answered by 30.03.2017 в 11:04