Recuperar todos los correos electrónicos no leídos usando javamail con el protocolo POP3


Estoy tratando de acceder a mi cuenta de gmail y recuperar la información de todos los correos electrónicos no leídos de eso.

He escrito mi código después de referir muchos enlaces. Estoy dando algunos enlaces para referencia.

Enviar y recibir correos electrónicos a través de una cuenta de GMail usando Java

Código Java para Recibir Correo usando JavaMailAPI

Para probar mi código, creé una cuenta de Gmail. Así que recibí 4 mensajes de Gmail. Corro mi aplicación después de comprobar el número de correos. Que mostró el resultado correcto. 4 correos no leídos. Se estaba mostrando toda la información (por ejemplo, fecha, remitente, contenido, asunto, etc.).)

Luego inicié sesión en mi nueva cuenta, leí uno de los correos electrónicos y volví a ejecutar mi aplicación. Ahora el conteo de mensajes no leídos debería haber sido 3, pero muestra "No. de Mensajes No leídos: 0 "

Estoy copiando el código aquí.

public class MailReader

{

    Folder inbox;

    // Constructor of the calss.

    public MailReader() {
        System.out.println("Inside MailReader()...");
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        /* Set the mail properties */

        Properties props = System.getProperties();
        // Set manual Properties
        props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.pop3.socketFactory.fallback", "false");
        props.setProperty("mail.pop3.port", "995");
        props.setProperty("mail.pop3.socketFactory.port", "995");
        props.put("mail.pop3.host", "pop.gmail.com");

        try

        {

            /* Create the session and get the store for read the mail. */

            Session session = Session.getDefaultInstance(
                    System.getProperties(), null);

            Store store = session.getStore("pop3");

            store.connect("pop.gmail.com", 995, "[email protected]",
                    "paasword");

            /* Mention the folder name which you want to read. */

            // inbox = store.getDefaultFolder();
            // inbox = inbox.getFolder("INBOX");
            inbox = store.getFolder("INBOX");

            /* Open the inbox using store. */

            inbox.open(Folder.READ_ONLY);

            /* Get the messages which is unread in the Inbox */

            Message messages[] = inbox.search(new FlagTerm(new Flags(
                    Flags.Flag.SEEN), false));
            System.out.println("No. of Unread Messages : " + messages.length);

            /* Use a suitable FetchProfile */
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);

            fp.add(FetchProfile.Item.CONTENT_INFO);

            inbox.fetch(messages, fp);

            try

            {

                printAllMessages(messages);

                inbox.close(true);
                store.close();

            }

            catch (Exception ex)

            {
                System.out.println("Exception arise at the time of read mail");

                ex.printStackTrace();

            }

        }

        catch (MessagingException e)
        {
            System.out.println("Exception while connecting to server: "
                    + e.getLocalizedMessage());
            e.printStackTrace();
            System.exit(2);
        }

    }

    public void printAllMessages(Message[] msgs) throws Exception
    {
        for (int i = 0; i < msgs.length; i++)
        {

            System.out.println("MESSAGE #" + (i + 1) + ":");

            printEnvelope(msgs[i]);
        }

    }

    public void printEnvelope(Message message) throws Exception

    {

        Address[] a;

        // FROM

        if ((a = message.getFrom()) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("FROM: " + a[j].toString());
            }
        }
        // TO
        if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("TO: " + a[j].toString());
            }
        }
        String subject = message.getSubject();

        Date receivedDate = message.getReceivedDate();
        Date sentDate = message.getSentDate(); // receivedDate is returning
                                                // null. So used getSentDate()

        String content = message.getContent().toString();
        System.out.println("Subject : " + subject);
        if (receivedDate != null) {
            System.out.println("Received Date : " + receivedDate.toString());
        }
        System.out.println("Sent Date : " + sentDate.toString());
        System.out.println("Content : " + content);

        getContent(message);

    }

    public void getContent(Message msg)

    {
        try {
            String contentType = msg.getContentType();
            System.out.println("Content Type : " + contentType);
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                dumpPart(mp.getBodyPart(i));
            }
        } catch (Exception ex) {
            System.out.println("Exception arise at get Content");
            ex.printStackTrace();
        }
    }

    public void dumpPart(Part p) throws Exception {
        // Dump input stream ..
        InputStream is = p.getInputStream();
        // If "is" is not already buffered, wrap a BufferedInputStream
        // around it.
        if (!(is instanceof BufferedInputStream)) {
            is = new BufferedInputStream(is);
        }
        int c;
        System.out.println("Message : ");
        while ((c = is.read()) != -1) {
            System.out.write(c);
        }
    }

    public static void main(String args[]) {
        new MailReader();
    }
}

Busqué en Google, pero descubrí que deberías usar banderas.Bandera.VISTO para leer correos electrónicos no leídos. Pero eso no es mostrando resultados correctos en mi caso.

¿Puede alguien señalar dónde podría estar cometiendo algún error?

Si necesitas código completo, puedo editar mi publicación.

Nota: Edité mi pregunta para incluir código completo en lugar de fragmento que había publicado anteriormente.

Author: Technotronic, 2012-10-30

6 answers

Su código debería funcionar. También puede utilizar la Carpeta.Método getUnreadMessageCount () si todo lo que quieres es el count.

JavaMail solo puede decirte lo que Gmail le dice. Tal vez Gmail piensa que todos esos mensajes han sido leídos? Tal vez la interfaz web de Gmail está marcando esos mensajes de lectura? Tal vez usted tiene otra aplicación de monitoreo de la carpeta de nuevos mensajes?

Intente leer un mensaje no leído con JavaMail y vea si el conteo cambia.

Puede que lo encuentres útil para activar la depuración de sesiones para que pueda ver las respuestas IMAP reales que Gmail está devolviendo; consulte el JavaMail FAQ .

 13
Author: Bill Shannon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-30 18:33:24

Cambiar inbox.open(Folder.READ_ONLY); a inbox.open(Folder.READ_WRITE); Cambiará su correo como leído en la bandeja de entrada.

 7
Author: user1791574,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-04 11:40:42

No puede recuperar mensajes no leídos con POP3. Desde JavaMail API :

POP3 no soporta banderas permanentes (ver Carpeta.getPermanentFlags()). En en particular, las banderas.Bandera.La bandera RECIENTE nunca se establecerá para POP3 mensaje. Depende de la aplicación determinar qué mensajes en un El buzón POP3 es "nuevo".

Puede usar el protocolo IMAP y usar la bandera VISTA de esta manera:

public Message[] fetchMessages(String host, String user, String password, boolean read) {
    Properties properties = new Properties();
    properties.put("mail.store.protocol", "imaps");

    Session emailSession = Session.getDefaultInstance(properties);
    Store store = emailSession.getStore();
    store.connect(host, user, password);

    Folder emailFolder = store.getFolder("INBOX");
    // use READ_ONLY if you don't wish the messages
    // to be marked as read after retrieving its content
    emailFolder.open(Folder.READ_WRITE);

    // search for all "unseen" messages
    Flags seen = new Flags(Flags.Flag.SEEN);
    FlagTerm unseenFlagTerm = new FlagTerm(seen, read);
    return emailFolder.search(unseenFlagTerm);
}

Otra cosa a tener en cuenta es que POP3 no maneja carpetas. IMAP obtiene carpetas, POP3 solo obtiene la bandeja de entrada. Más información en: ¿Cómo recuperar subcarpetas/etiquetas de gmail usando POP3?

 7
Author: Technotronic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:27
Flags seen = new Flags(Flags.Flag.RECENT);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
messages = inbox.search(unseenFlagTerm);
 1
Author: ibrahimKiraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-04 11:35:36

La bandera correcta a usar es

Flags.Flag.RECENT
 1
Author: user1397305,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-19 09:35:27

Utilice este método para obtener los correos no leídos

GetNewMessageCount ()

Consulte el siguiente enlace:

Https://javamail.java.net/nonav/docs/api/com/sun/mail/imap/IMAPFolder.html

 -1
Author: vidhyadhar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-22 05:25:35