Example usage for javax.mail Folder READ_WRITE

List of usage examples for javax.mail Folder READ_WRITE

Introduction

In this page you can find the example usage for javax.mail Folder READ_WRITE.

Prototype

int READ_WRITE

To view the source code for javax.mail Folder READ_WRITE.

Click Source Link

Document

The state and contents of this folder can be modified.

Usage

From source file:monitor.java

public static void main(String argv[]) {
    if (argv.length != 5) {
        System.out.println("Usage: monitor <host> <user> <password> <mbox> <freq>");
        System.exit(1);/*  www. j  a  v  a 2 s .c  o m*/
    }
    System.out.println("\nTesting monitor\n");

    try {
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        // session.setDebug(true);

        // Get a Store object
        Store store = session.getStore("imap");

        // Connect
        store.connect(argv[0], argv[1], argv[2]);

        // Open a Folder
        Folder folder = store.getFolder(argv[3]);
        if (folder == null || !folder.exists()) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        folder.open(Folder.READ_WRITE);

        // Add messageCountListener to listen for new messages
        folder.addMessageCountListener(new MessageCountAdapter() {
            public void messagesAdded(MessageCountEvent ev) {
                Message[] msgs = ev.getMessages();
                System.out.println("Got " + msgs.length + " new messages");

                // Just dump out the new messages
                for (int i = 0; i < msgs.length; i++) {
                    try {
                        System.out.println("-----");
                        System.out.println("Message " + msgs[i].getMessageNumber() + ":");
                        msgs[i].writeTo(System.out);
                    } catch (IOException ioex) {
                        ioex.printStackTrace();
                    } catch (MessagingException mex) {
                        mex.printStackTrace();
                    }
                }
            }
        });

        // Check mail once in "freq" MILLIseconds
        int freq = Integer.parseInt(argv[4]);
        boolean supportsIdle = false;
        try {
            if (folder instanceof IMAPFolder) {
                IMAPFolder f = (IMAPFolder) folder;
                f.idle();
                supportsIdle = true;
            }
        } catch (FolderClosedException fex) {
            throw fex;
        } catch (MessagingException mex) {
            supportsIdle = false;
        }
        for (;;) {
            if (supportsIdle && folder instanceof IMAPFolder) {
                IMAPFolder f = (IMAPFolder) folder;
                f.idle();
                System.out.println("IDLE done");
            } else {
                Thread.sleep(freq); // sleep for freq milliseconds

                // This is to force the IMAP server to send us
                // EXISTS notifications. 
                folder.getMessageCount();
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:copier.java

public static void main(String argv[]) {
    boolean debug = false; // change to get more errors

    if (argv.length != 5) {
        System.out.println("usage: copier <urlname> <src folder>" + "<dest folder> <start msg #> <end msg #>");
        return;/*from w w w .  jav  a 2  s .  c  o  m*/
    }

    try {
        URLName url = new URLName(argv[0]);
        String src = argv[1]; // source folder
        String dest = argv[2]; // dest folder
        int start = Integer.parseInt(argv[3]); // copy from message #
        int end = Integer.parseInt(argv[4]); // to message #

        // Get the default Session object

        Session session = Session.getInstance(System.getProperties(), null);
        // session.setDebug(debug);

        // Get a Store object that implements the protocol.
        Store store = session.getStore(url);
        store.connect();
        System.out.println("Connected...");

        // Open Source Folder
        Folder folder = store.getFolder(src);
        folder.open(Folder.READ_WRITE);
        System.out.println("Opened source...");

        if (folder.getMessageCount() == 0) {
            System.out.println("Source folder has no messages ..");
            folder.close(false);
            store.close();
        }

        // Open destination folder, create if needed 
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists()) // create
            dfolder.create(Folder.HOLDS_MESSAGES);

        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Got messages...");

        // Copy messages into destination, 
        folder.copyMessages(msgs, dfolder);
        System.out.println("Copied messages...");

        // Close the folder and store
        folder.close(false);
        store.close();
        System.out.println("Closed folder and store...");

    } catch (Exception e) {
        e.printStackTrace();
    }

    System.exit(0);
}

From source file:MainClass.java

public static void main(String argv[]) {
    boolean debug = false;// change to get more errors

    if (argv.length != 5) {
        System.out.println("usage: copier <urlname> <src folder>" + "<dest folder> <start msg #> <end msg #>");
        return;/*  w w  w.  j  a v  a  2 s. c o  m*/
    }

    try {
        URLName url = new URLName(argv[0]);
        String src = argv[1]; // source folder
        String dest = argv[2]; // dest folder
        int start = Integer.parseInt(argv[3]); // copy from message #
        int end = Integer.parseInt(argv[4]); // to message #

        // Get the default Session object

        Session session = Session.getInstance(System.getProperties(), null);
        // session.setDebug(debug);

        // Get a Store object that implements
        // the protocol.
        Store store = session.getStore(url);
        store.connect();
        System.out.println("Connected...");

        // Open Source Folder
        Folder folder = store.getFolder(src);
        folder.open(Folder.READ_WRITE);
        System.out.println("Opened source...");

        if (folder.getMessageCount() == 0) {
            System.out.println("Source folder has no messages ..");
            folder.close(false);
            store.close();
        }

        // Open destination folder, create if needed
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists()) // create
            dfolder.create(Folder.HOLDS_MESSAGES);

        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Got messages...");

        // Copy messages into destination,
        folder.copyMessages(msgs, dfolder);
        System.out.println("Copied messages...");

        // Close the folder and store
        folder.close(false);
        store.close();
        System.out.println("Closed folder and store...");

    } catch (Exception e) {
        e.printStackTrace();
    }

    System.exit(0);
}

From source file:mover.java

public static void main(String argv[]) {
    int start = 1;
    int end = -1;
    int optind;//from  w  w w.  j a  va 2 s  .co  m

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) { // protocol
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) { // host
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) { // user
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) { // password
            password = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-s")) { // Source mbox
            src = argv[++optind];
        } else if (argv[optind].equals("-d")) { // Destination mbox
            dest = argv[++optind];
        } else if (argv[optind].equals("-x")) { // Expunge ?
            expunge = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: mover [-T protocol] [-H host] [-U user] [-P password] [-L url] [-v]");
            System.out.println("\t[-s source mbox] [-d destination mbox] [-x] [msgnum1] [msgnum2]");
            System.out.println("\t The -x option => EXPUNGE deleted messages");
            System.out.println("\t msgnum1 => start of message-range; msgnum2 => end of message-range");
            System.exit(1);
        } else {
            break;
        }
    }

    if (optind < argv.length)
        start = Integer.parseInt(argv[optind++]); // start msg

    if (optind < argv.length)
        end = Integer.parseInt(argv[optind++]); // end msg

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, user, password);
            else
                store.connect();
        }

        // Open source Folder
        Folder folder = store.getFolder(src);
        if (folder == null || !folder.exists()) {
            System.out.println("Invalid folder: " + src);
            System.exit(1);
        }

        folder.open(Folder.READ_WRITE);

        int count = folder.getMessageCount();
        if (count == 0) { // No messages in the source folder
            System.out.println(folder.getName() + " is empty");
            // Close folder, store and return
            folder.close(false);
            store.close();
            return;
        }

        // Open destination folder, create if reqd
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists())
            dfolder.create(Folder.HOLDS_MESSAGES);

        if (end == -1)
            end = count;

        // Get the message objects to copy
        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Moving " + msgs.length + " messages");

        if (msgs.length != 0) {
            folder.copyMessages(msgs, dfolder);
            folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);

            // Dump out the Flags of the moved messages, to insure that
            // all got deleted
            for (int i = 0; i < msgs.length; i++) {
                if (!msgs[i].isSet(Flags.Flag.DELETED))
                    System.out.println("Message # " + msgs[i] + " not deleted");
            }
        }

        // Close folders and store
        folder.close(expunge);
        store.close();

    } catch (MessagingException mex) {
        Exception ex = mex;
        do {
            System.out.println(ex.getMessage());
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:uidmsgshow.java

public static void main(String argv[]) {
    long uid = -1;
    int optind;/*from  w  ww  . j a  v  a  2 s .c om*/

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println(
                    "Usage: uidmsgshow [-L url] [-T protocol] [-H host] [-U user] [-P password] [-f mailbox] [uid] [-v]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length)
            uid = Long.parseLong(argv[optind]);

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        // session.setDebug(true);

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        folder = folder.getFolder(mbox);
        if (!folder.exists()) {
            System.out.println(mbox + "  does not exist");
            System.exit(1);
        }

        if (!(folder instanceof UIDFolder)) {
            System.out.println("This Provider or this folder does not support UIDs");
            System.exit(1);
        }

        UIDFolder ufolder = (UIDFolder) folder;

        folder.open(Folder.READ_WRITE);
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (uid == -1) {
            // Attributes & Flags for ALL messages ..
            Message[] msgs = ufolder.getMessagesByUID(1, UIDFolder.LASTUID);

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE UID #" + ufolder.getUID(msgs[i]) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            System.out.println("Getting message UID: " + uid);
            Message m = ufolder.getMessageByUID(uid);
            if (m != null)
                dumpPart(m);
            else
                System.out.println("This Message does not exist on this folder");
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
    }
    System.exit(1);
}

From source file:MainClass.java

public static void main(String argv[]) {
    int start = 1;
    int end = -1;
    int optind;/*  ww w.ja va  2 s.c  o  m*/

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) { // protocol
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) { // host
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) { // user
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) { // password
            password = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-s")) { // Source mbox
            src = argv[++optind];
        } else if (argv[optind].equals("-d")) { // Destination mbox
            dest = argv[++optind];
        } else if (argv[optind].equals("-x")) { // Expunge ?
            expunge = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: mover [-T protocol] [-H host] [-U user] [-P password] [-L url] [-v]");
            System.out.println("\t[-s source mbox] [-d destination mbox] [-x] [msgnum1] [msgnum2]");
            System.out.println("\t The -x option => EXPUNGE deleted messages");
            System.out.println("\t msgnum1 => start of message-range; msgnum2 => end of message-range");
            System.exit(1);
        } else {
            break;
        }
    }

    if (optind < argv.length)
        start = Integer.parseInt(argv[optind++]); // start msg

    if (optind < argv.length)
        end = Integer.parseInt(argv[optind++]); // end msg

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, user, password);
            else
                store.connect();
        }

        // Open source Folder
        Folder folder = store.getFolder(src);
        if (folder == null || !folder.exists()) {
            System.out.println("Invalid folder: " + folder.getName());
            System.exit(1);
        }

        folder.open(Folder.READ_WRITE);

        int count = folder.getMessageCount();
        if (count == 0) { // No messages in the source folder
            System.out.println(folder.getName() + " is empty");
            // Close folder, store and return
            folder.close(false);
            store.close();
            return;
        }

        // Open destination folder, create if reqd
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists())
            dfolder.create(Folder.HOLDS_MESSAGES);

        if (end == -1)
            end = count;

        // Get the message objects to copy
        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Moving " + msgs.length + " messages");

        if (msgs.length != 0) {
            folder.copyMessages(msgs, dfolder);
            folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);

            // Dump out the Flags of the moved messages, to insure that
            // all got deleted
            for (int i = 0; i < msgs.length; i++) {
                if (!msgs[i].isSet(Flags.Flag.DELETED))
                    System.out.println("Message # " + msgs[i] + " not deleted");
            }
        }

        // Close folders and store
        folder.close(expunge);
        store.close();

    } catch (MessagingException mex) {
        Exception ex = mex;
        do {
            System.out.println(ex.getMessage());
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:msgshow.java

public static void main(String argv[]) {
    int optind;/*from ww  w .  j  a  v  a2  s  .  c  o m*/
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (optind >= argv.length) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            while (optind < argv.length) {
                int msgnum = Integer.parseInt(argv[optind++]);
                System.out.println("Getting message number: " + msgnum);
                Message m = null;

                try {
                    m = folder.getMessage(msgnum);
                    dumpPart(m);
                } catch (IndexOutOfBoundsException iex) {
                    System.out.println("Message number out of range");
                }
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:MainClass.java

public static void main(String argv[]) {
    int msgnum = -1;
    int optind;/*from w  w w  . j  a  v  a2  s  . co m*/
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length)
            msgnum = Integer.parseInt(argv[optind]);

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (msgnum == -1) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            System.out.println("Getting message number: " + msgnum);
            Message m = null;

            try {
                m = folder.getMessage(msgnum);
                dumpPart(m);
            } catch (IndexOutOfBoundsException iex) {
                System.out.println("Message number out of range");
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:org.springframework.ws.transport.mail.monitor.AbstractMonitoringStrategy.java

public int getFolderOpenMode() {
    return deleteMessages ? Folder.READ_WRITE : Folder.READ_ONLY;
}

From source file:nl.ordina.bag.etl.mail.loader.IMAPMutatiesFileLoader.java

@Override
public void processMessages() {
    try {/*from  www.  jav  a  2s  .  c o m*/
        Session session = Session.getDefaultInstance(new Properties(), null);
        Store store = session.getStore(protocol);
        if (port == 0)
            store.connect(host, username, password);
        else
            store.connect(host, port, username, password);

        Folder folder = store.getFolder(folderName);
        if (folder == null)
            throw new RuntimeException("Folder " + folderName + " not found!");
        folder.open(Folder.READ_WRITE);

        try {
            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            Message messages[] = folder.search(ft);
            for (Message message : messages) {
                messageHandler.handle(message);
                message.setFlags(new Flags(Flags.Flag.SEEN), true);
            }
        } finally {
            folder.close(true);
            store.close();
        }
    } catch (MessagingException | IOException | JAXBException e) {
        throw new ProcessingException(e);
    }
}