Example usage for javax.mail Folder HOLDS_MESSAGES

List of usage examples for javax.mail Folder HOLDS_MESSAGES

Introduction

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

Prototype

int HOLDS_MESSAGES

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

Click Source Link

Document

This folder can contain messages

Usage

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  ww.j ava 2 s .com*/
    }

    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;//ww w.  j a v a 2s  .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  ww  w.  j  a  v  a 2  s  .c  om*/

    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:MainClass.java

public static void main(String argv[]) {
    int start = 1;
    int end = -1;
    int optind;//from   w  w w.  ja v  a2  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: " + 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:msgsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//ww  w . ja v a  2  s.co  m
    String mailer = "msgsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    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("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-a attach-file] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

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

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != 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();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

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

From source file:smtpsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//ww w . ja va2  s .  co  m
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    boolean ssl = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    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("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            ssl = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);
        if (auth)
            props.put("mail.smtp.auth", "true");

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

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        /*
         * The simple way to send a message is this:
         * 
         * Transport.send(msg);
         * 
         * But we're going to use some SMTP-specific features for demonstration
         * purposes so we need to manage the Transport object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != 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();
            }

            // Get record Folder. Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}

From source file:smtpsend.java

/**
 * Example of how to extend the SMTPTransport class.
 * This example illustrates how to issue the XACT
 * command before the SMTPTransport issues the DATA
 * command./*from ww w.  ja v  a 2 s . c om*/
 *
public static class SMTPExtension extends SMTPTransport {
public SMTPExtension(Session session, URLName url) {
   super(session, url);
   // to check that we're being used
   System.out.println("SMTPExtension: constructed");
}
        
protected synchronized OutputStream data() throws MessagingException {
   if (supportsExtension("XACCOUNTING"))
  issueCommand("XACT", 250);
   return super.data();
}
}
 */

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    String prot = "smtp";
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    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("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            prot = "smtps";
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail." + prot + ".host", mailhost);
        if (auth)
            props.put("mail." + prot + ".auth", "true");

        /*
         * Create a Provider representing our extended SMTP transport
         * and set the property to use our provider.
         *
        Provider p = new Provider(Provider.Type.TRANSPORT, prot,
        "smtpsend$SMTPExtension", "JavaMail demo", "no version");
        props.put("mail." + prot + ".class", "smtpsend$SMTPExtension");
         */

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

        /*
         * Register our extended SMTP transport.
         *
        session.addProvider(p);
         */

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        /*
         * The simple way to send a message is this:
         *
        Transport.send(msg);
         *
         * But we're going to use some SMTP-specific features for
         * demonstration purposes so we need to manage the Transport
         * object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(prot);
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != 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();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        /*
         * Handle SMTP-specific exceptions.
         */
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}

From source file:org.apache.hupa.server.handler.CreateFolderHandler.java

@Override
protected GenericResult executeInternal(CreateFolder action, ExecutionContext context) throws ActionException {
    User user = getUser();/*from   w w w . j a  v a  2 s. c o  m*/
    IMAPFolder folder = action.getFolder();

    try {
        IMAPStore store = cache.get(user);
        Folder f = store.getFolder(folder.getFullName());
        if (f.create(Folder.HOLDS_MESSAGES)) {
            logger.info("Successfully create folder " + folder + " for user " + user);
            return new GenericResult();
        } else {
            logger.info("Unable to create folder " + folder + " for user " + user);
            throw new ActionException("Unable to create folder " + folder + " for user " + user);

        }
    } catch (Exception e) {
        logger.error("Error while creating folder " + folder + " for user " + user, e);
        throw new ActionException("Error while creating folder " + folder + " for user " + user, e);
    }
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * @param folder//from   w w w  .  ja  va 2 s . c om
 * @param message
 * @throws MessagingException
 */
public void write(String folder, Message message) throws MessagingException {
    // getLogger().info("Delivering " + message + " to " + this.location + " / " + folder);

    final Store store = getJavamailStore(true);
    store.connect();
    final Folder mailFolder = store.getDefaultFolder().getFolder(folder);
    if (!mailFolder.exists()) {
        mailFolder.create(Folder.HOLDS_MESSAGES);
    }
    mailFolder.open(Folder.READ_WRITE);
    // If message is already archived, do nothing
    final Message existingMessage = read(folder, message.getHeader("Message-ID")[0]);
    if (existingMessage == null) {
        // The Store Provider may add some headers to the message to store, but IMAPMessage are read-only
        // So we clone the message before storing it
        final MimeMessage cloned = cloneEmail(message);
        mailFolder.appendMessages(new Message[] { cloned });
    }

    mailFolder.close(true);
    store.close();
}

From source file:org.jasig.portlet.emailpreview.controller.AjaxUpdateInboxFolderController.java

@ResourceMapping("inboxFolder")
public ModelAndView inboxFolder(ResourceRequest req, ResourceResponse res) throws MessagingException {
    IEmailAccountService accountDao = serviceBroker.getEmailAccountService(req);

    PortletPreferences prefs = req.getPreferences();
    String selectedFolder = prefs.getValue(EmailAccountSummaryController.INBOX_NAME_PREFERENCE,
            INBOX_DEFAULT_VALUE_PREF);/*w ww .j a  v a 2s . c o m*/
    String authenticationServiceKey = prefs.getValue(AUTH_SERVICE_PREFERENCE,
            AUTH_SERVICE_DEFAULT_VALUE_PREFERENCE);

    Map<String, String> jsonData = new Hashtable<String, String>();

    if (AUTH_SERVICE_TEST_PREFERENCE.equals(authenticationServiceKey)) {
        jsonData.put("INBOX", "INBOX");
        //For demo : must have the same name that the json files in src/main/resources
        jsonData.put("demoTest", "demoTest");
        jsonData.put("Important", "Important");
        for (Map.Entry<String, String> entry : jsonData.entrySet()) {
            if (entry.getValue().equals(selectedFolder)) {
                jsonData.put(SELECTED_OPTION, entry.getValue());
                break;
            }
        }
    } else {
        for (Folder folderName : accountDao.getAllUserInboxFolders(req)) {
            if ((folderName.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
                String unreadMsgCount = "";
                if (folderName.getUnreadMessageCount() != 0
                        && (!selectedFolder.equals(folderName.toString()))) {
                    unreadMsgCount = " (".concat(String.valueOf(folderName.getUnreadMessageCount())).concat(")")
                            .concat(UNREAD_MSG_FLAG);
                }
                jsonData.put(folderName.toString().concat(unreadMsgCount), folderName.toString());
                if (selectedFolder.equals(folderName.toString())) {
                    jsonData.put(SELECTED_OPTION, folderName.toString());
                }
            }
        }
    }
    return new ModelAndView("json", jsonData);
}