tags:

views:

31

answers:

1

I am working on a project using JavaMail. I want to access my Gmail inbox and get the messages. I look for a specific message by checking the subject. This message has an attachment which i save.The program works fine on the first run. The problem is that once I run the program, any subsequent runs can not see the message. It does not appear as a part of the folder's messages. If I go to the gmail account and set "Enable POP for all mail (even mail that's already been downloaded)" (whihc was the setting from the beginning) I can see the message once more before it again stops appearing in the folder. I dont understand, any help would be great.

Here is my code that gets the messages:

    Session session2 = Session.getDefaultInstance(props2, null);
    Store store = session2.getStore("pop3s");
    store.connect(getHost, username, password);
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);
    System.out.println(folder.getMessageCount());
    Message messages[] = folder.getMessages();
    for (Message message : messages) {
        System.out.println(message.getSubject());
        if (message.getSubject().equalsIgnoreCase("Input File")) {
            if (message.getContent() instanceof Multipart) {
                Multipart multipart = (Multipart) message.getContent();
                for (int i = 0, n = multipart.getCount(); i < n; i++) {
                    Part part = multipart.getBodyPart(i);
                    String disposition = part.getDisposition();
                    if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
                        File f = saveFile(part.getFileName(), part.getInputStream());
                        System.out.println(f.getPath());
                    }
                }
            }
        }
    }
    folder.close(false);
    store.close();
}

The saveFile method:

public static File saveFile(String filename, InputStream input) throws FileNotFoundException, IOException {
    File file = new File(filename);
    for (int i = 0; file.exists(); i++) {
        file = new File(filename + i);
    }
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    BufferedInputStream bis = new BufferedInputStream(input);
    int aByte;
    while ((aByte = bis.read()) != -1) {
        bos.write(aByte);
    }
    bos.flush();
    bos.close();
    bis.close();
    return file;
}
A: 

I tried switching my code to using imap and now it seems to be working. I guess my problem has something to do with pop3 and gmail.

SomeFatMan