rishabhkeshari123
rishabhkeshari123

Reputation: 143

POP3 protocol but not getting unread mails correctly

I have some code to download attachments from unread mails the code downloading attachments properly,But it is downloading attachment from a certain date, it should download attachment from unread mails only.below i am attaching code.

    package filread.oneline;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * This program demonstrates how to download e-mail messages and save
 * attachments into files on disk.
 *
 * @author www.codejava.net
 *
 */
public class EmailAttachmentReceiver {
    private String saveDirectory;

    /**
     * Sets the directory where attached files will be stored.
     * @param dir absolute path of the directory
     */
    public void setSaveDirectory(String dir) {
        this.saveDirectory = dir;
    }

    /**
     * Downloads new messages and saves attachments to disk if any.
     * @param host
     * @param port
     * @param userName
     * @param password
     */
    public void downloadEmailAttachments(String host, String port,
            String userName, String password) {
        Properties properties = new Properties();

        // server setting
       properties.put("mail.smtp.starttls.enable",true);
       properties.put("mail.pop3.host", host);
       properties.put("mail.pop3.port", port);
        properties.put("mail.store.protocol", "pop3");
        // SSL setting
      // properties.put("mail.pop3.socketFactory.class","javax.net.ssl.SSLSocketFactory");
       properties.put("mail.pop3.socketFactory.fallback", false);


      //  properties.setProperty("mail.smtp.auth", "true");

      // properties.put("mail.pop3.socketFactory.port",String.valueOf(port));

        Session session = Session.getDefaultInstance(properties);

        try {
            // connects to the message store
            Store store = session.getStore("pop3");
            store.connect("mail.vidalhealthtpa.com",userName, password);

            // opens the inbox folder
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);
            System.out.println("No of Unread Messages : " + folderInbox.getUnreadMessageCount());

            // fetches new messages from server
           // Message[] arrayMessages = folderInbox.getMessages();
            Message[]  arrayMessages = folderInbox.search(new FlagTerm(new Flags(Flag.SEEN), false));


            for (int i = 0; i < arrayMessages.length; i++) {
                Message message = arrayMessages[i];
                Address[] fromAddress = message.getFrom();
                String from = fromAddress[0].toString();
                String subject = message.getSubject();
                String sentDate = message.getSentDate().toString();

                String contentType = message.getContentType();
                String messageContent = "";

                // store attachment file name, separated by comma
                String attachFiles = "";

                if (contentType.contains("multipart")) {
                    // content may contain attachments
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // this part is attachment
                            String fileName = part.getFileName();
                            attachFiles += fileName + ", ";

                           byte[] abcd=IOUtils.toByteArray(part.getInputStream());
                           System.out.println("No of Unread Messages : " + folderInbox.getUnreadMessageCount());

                           System.out.println("No of Unread Messages : " + folderInbox.getNewMessageCount());

                           System.out.println("No of Unread Messages : " + folderInbox.getMessageCount());
                           System.out.println("No of Unread Messages : " + arrayMessages.length);


                           FileUtils.writeByteArrayToFile(new File(saveDirectory + File.separator + fileName), abcd);



                          //  part.saveFile(saveDirectory + File.separator + fileName);

                        } else {
                            // this part may be the message content
                            messageContent = part.getContent().toString();
                        }
                    }

                    if (attachFiles.length() > 1) {
                        attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                    }
                } else if (contentType.contains("text/plain")
                        || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }

                // print out details of each message
                System.out.println("Message #" + (i + 1) + ":");
                System.out.println("\t From: " + from);
                System.out.println("\t Subject: " + subject);
                System.out.println("\t Sent Date: " + sentDate);
                System.out.println("\t Message: " + messageContent);
                System.out.println("\t Attachments: " + attachFiles);
            }

            // disconnect
            folderInbox.close(false);
            store.close();
        } catch (NoSuchProviderException ex) {
            System.out.println("No provider for pop3.");
            ex.printStackTrace();
        } catch (MessagingException ex) {
            System.out.println("Could not connect to the message store");
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Runs this program with Gmail POP3 server
     */
    public static void main(String[] args) {
        String host = "host";
        String port = "110";
        String userName = "username";
        String password = "password";

        String saveDirectory = "D:/Attachment";

        EmailAttachmentReceiver receiver = new EmailAttachmentReceiver();
        receiver.setSaveDirectory(saveDirectory);
        receiver.downloadEmailAttachments(host, port, userName, password);

    }
}

I can't able to guess what issue ,why the code is not reading UNREAD MAILS only, its reading all mails and downloading all attachments.

Upvotes: 0

Views: 930

Answers (2)

rishabhkeshari123
rishabhkeshari123

Reputation: 143

package MAIL.READ.ATTACHEMENT;


import java.io.File;
import java.io.IOException;
import java.util.Properties;







import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;
import javax.mail.search.SearchTerm;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class ReadMailAttachement {
    private String saveDirectory;

    public void setSaveDirectory(String dir) {
        this.saveDirectory = dir;
    }

    public void downloadEmailAttachments(String host, String port,
            String userName, String password) {
        Properties properties = new Properties();

        // server setting
    /*  properties.put("mail.smtp.starttls.enable",true);*/
     properties.put("mail.imap.host", host);
   //  properties.put("mail.store.protocol", "imaps");
     /* properties.put("mail.imap.port", port);
       */
        // SSL setting
 /*     properties.put("mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    properties.put("mail.imap.socketFactory.fallback", false);*/


      //  properties.setProperty("mail.smtp.auth", "true");

      // properties.put("mail.pop3.socketFactory.port",String.valueOf(port));

        Session session = Session.getDefaultInstance(properties);

        try {
             Store store = session.getStore("imap");
            store.connect("mail.vidalhealthtpa.com",userName, password);
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_WRITE);
            System.out.println("No of Unread Messages : " + folderInbox.getUnreadMessageCount());


          Message[] arrayMessages1 = folderInbox.getMessages();
         Message[]  arrayMessages = folderInbox.search(new FlagTerm(new Flags(Flag.SEEN), false),arrayMessages1);

        System.out.println("    jjj  arrayMessages.length 0   "+arrayMessages.length);

            for (int i = 0; i < arrayMessages.length; i++) {
                Message message = arrayMessages[i];
                Address[] fromAddress = message.getFrom();
                String from = fromAddress[0].toString();
                String subject = message.getSubject();
                String sentDate = message.getSentDate().toString();

               message.setFlag(Flags.Flag.SEEN, true);

                String contentType = message.getContentType();
                String messageContent = "";

                // store attachment file name, separated by pipeline
                String attachFiles = "|";

                if (contentType.contains("multipart")) {
                    // content may contain attachments
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {

                            // this part is attachment
                            String fileName = part.getFileName();
                            attachFiles += fileName + "|";




                           byte[] FileByteData=IOUtils.toByteArray(part.getInputStream());
                         FileUtils.writeByteArrayToFile(new File(saveDirectory + File.separator + fileName), FileByteData);







                          //  part.saveFile(saveDirectory + File.separator + fileName);

                        } else {
                            // this part may be the message content
                            messageContent = part.getContent().toString();
                        }
                    }

                   /* if (attachFiles.length() > 1) {
                        attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                    }*/

                } else if (contentType.contains("text/plain")|| contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }

                // print out details of each message
                System.out.println("Message #" + (i + 1) + ":");
                System.out.println("\t From: " + from);
                System.out.println("\t Subject: " + subject);
                System.out.println("\t Sent Date: " + sentDate);
                System.out.println("\t Message: " + messageContent);
                System.out.println("\t Attachments: " + attachFiles);
            }

            folderInbox.close(false);
            store.close();
        } catch (NoSuchProviderException ex) {
            System.out.println("No provider for pop3.");
            ex.printStackTrace();
        } catch (MessagingException ex) {
            System.out.println("Could not connect to the message store");
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String host = "host";
        String port = "110";
        //String userName = "user";
       // String password = "password";

        String userName = "rishabh.keshari";
        String password = "TuY$&Q130";

        String saveDirectory = "D:/Attachment";

        ReadMailAttachement receiver = new ReadMailAttachement();
        receiver.setSaveDirectory(saveDirectory);
        receiver.downloadEmailAttachments(host, port, userName, password);

    }
}

I am setting flag seen as a true for read mail

message.setFlag(Flags.Flag.SEEN, true);

Upvotes: 0

Bill Shannon
Bill Shannon

Reputation: 29971

The POP3 protocol doesn't support any message flags so there's no way to know what messages are read or unread. See the com.sun.mail.pop3 package documentation for more information.

If at all possible, you should use the IMAP protocol.

Upvotes: 2

Related Questions