Java Tutorial/Email/Email Server

Материал из Java эксперт
Версия от 15:23, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Copy a specified number of messages from one folder to another folder

/*
 * @(#)copier.java  1.10 06/04/17
 *
 * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
 * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
 * SUFFERED BY LICENSEE AS A RESULT OF  OR RELATING TO USE, MODIFICATION
 * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
 * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
 * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that Software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/**
 *
 * @version 1.10, 06/04/17
 * @author  Christopher Cotton
 */
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
/**
 * copier will copy a specified number of messages from one folder to another
 * folder. it demonstrates how to use the JavaMail APIs to copy messages.
 * <P>
 * 
 * usage for copier: copier <i>protocol</i> <i>host</i> <i>user</i>
 * <i>password</i> <i>src folder</i> <i>dest folder</i> <i>start msg #</i>
 * <i>end msg #</i>
 * <P>
 * 
 */
public class MainClass {
  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;
    }
    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);
  }
}





Copy folder hierarchies between different Stores

/*
 * @(#)populate.java  1.12 06/02/28
 *
 * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
 * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
 * SUFFERED BY LICENSEE AS A RESULT OF  OR RELATING TO USE, MODIFICATION
 * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
 * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
 * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that Software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage;
/*
 * Copy folder hierarchies between different Stores. This is a useful utility to
 * populate new (and possibly empty) mail stores. Specify both the source and
 * destination folders as URLs.
 * 
 * @author John Mani @author Bill Shannon
 */
public class populate {
  static boolean force = false;
  static boolean skipSpecial = false;
  static boolean clear = false;
  static boolean dontPreserveFlags = false;
  public static void main(String argv[]) {
    String srcURL = null;
    String dstURL = null;
    boolean debug = false;
    int optind;
    for (optind = 0; optind < argv.length; optind++) {
      if (argv[optind].equals("-s")) {
        srcURL = argv[++optind];
      } else if (argv[optind].equals("-d")) {
        dstURL = argv[++optind];
      } else if (argv[optind].equals("-D")) {
        debug = true;
      } else if (argv[optind].equals("-f")) {
        force = true;
      } else if (argv[optind].equals("-S")) {
        skipSpecial = true;
      } else if (argv[optind].equals("-c")) {
        clear = true;
      } else if (argv[optind].equals("-P")) {
        dontPreserveFlags = true;
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        printUsage();
        System.exit(1);
      } else {
        break;
      }
    }
    try {
      if (srcURL == null || dstURL == null) {
        printUsage();
        System.exit(1);
      }
      Session session = Session.getInstance(System.getProperties(), null);
      session.setDebug(debug);
      // Get source folder
      URLName srcURLName = new URLName(srcURL);
      Folder srcFolder;
      // Check if the source URL has a folder specified. If
      // not, we use the default folder
      if (srcURLName.getFile() == null) {
        Store s = session.getStore(srcURLName);
        s.connect();
        srcFolder = s.getDefaultFolder();
      } else {
        srcFolder = session.getFolder(new URLName(srcURL));
        if (!srcFolder.exists()) {
          System.out.println("source folder does not exist");
          srcFolder.getStore().close();
          System.exit(1);
        }
      }
      // Set up destination folder
      URLName dstURLName = new URLName(dstURL);
      Folder dstFolder;
      // Check if the destination URL has a folder specified. If
      // not, we use the source folder name
      if (dstURLName.getFile() == null) {
        Store s = session.getStore(dstURLName);
        s.connect();
        dstFolder = s.getFolder(srcFolder.getName());
      } else
        dstFolder = session.getFolder(dstURLName);
      if (clear && dstFolder.exists()) {
        if (!dstFolder.delete(true)) {
          System.out.println("couldn"t delete " + dstFolder.getFullName());
          return;
        }
      }
      copy(srcFolder, dstFolder);
      // Close the respective stores.
      srcFolder.getStore().close();
      dstFolder.getStore().close();
    } catch (MessagingException mex) {
      System.out.println(mex.getMessage());
      mex.printStackTrace();
    }
  }
  private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());
    Folder ddst = dst;
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
      srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;
    if (!dst.exists()) {
      // Create it.
      boolean dstHoldsOnlyFolders = false;
      try {
        if (!dst.create(src.getType())) {
          System.out.println("couldn"t create " + dst.getFullName());
          return;
        }
      } catch (MessagingException mex) {
        // might not be able to create a folder that holds both
        if (src.getType() != (Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS))
          throw mex;
        if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
          System.out.println("couldn"t create " + dst.getFullName());
          return;
        }
        dstHoldsOnlyFolders = srcHasChildren;
      }
      // Copy over any messges from src to dst
      if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
        src.open(Folder.READ_ONLY);
        if (dstHoldsOnlyFolders) {
          if (src.getMessageCount() > 0) {
            System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                + dst.getFullName() + " because destination holds only folders");
          }
        } else
          copyMessages(src, dst);
        src.close(false);
      }
    } else {
      System.out.println(dst.getFullName() + " already exists");
      // Copy over any messges from src to dst
      if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
        src.open(Folder.READ_ONLY);
        copyMessages(src, dst);
        src.close(false);
      }
    }
    // Copy over subfolders
    if (srcHasChildren) {
      for (int i = 0; i < srcFolders.length; i++) {
        // skip special directories?
        if (skipSpecial) {
          if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
              || srcFolders[i].getName().equals("Trash")
              || srcFolders[i].getName().equals("Shared Folders"))
            continue;
        }
        copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
      }
    }
  }
  /**
   * Copy message from src to dst. If dontPreserveFlags is set we first copy the
   * messages to memory, clear all the flags, and then copy to the destination.
   */
  private static void copyMessages(Folder src, Folder dst) throws MessagingException {
    Message[] msgs = src.getMessages();
    if (dontPreserveFlags) {
      for (int i = 0; i < msgs.length; i++) {
        MimeMessage m = new MimeMessage((MimeMessage) msgs[i]);
        m.setFlags(m.getFlags(), false);
        msgs[i] = m;
      }
    }
    src.copyMessages(msgs, dst);
  }
  private static void printUsage() {
    System.out.println("populate [-D] [-f] [-S] [-c] " + "-s source_url -d dest_url");
    System.out.println("URLs are of the form: "
        + "protocol://username:password@hostname/foldername");
    System.out.println("The destination URL does not need a foldername,"
        + " in which case, the source foldername is used");
  }
}





Get All Message On Server

import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.URLName;
public class MainClass {
  public static void main(String[] args) throws Exception {
    URLName server = new URLName("protocol://username:password@host/foldername");
    Session session = Session.getDefaultInstance(new Properties(), null);
    Folder folder = session.getFolder(server);
    if (folder == null) {
      System.out.println("Folder " + server.getFile() + " not found.");
      System.exit(1);
    }
    folder.open(Folder.READ_ONLY);
    // Get the messages from the server
    Message[] messages = folder.getMessages();
    for (int i = 0; i < messages.length; i++) {
      System.out.println("------------ Message " + (i + 1) + " ------------");
      messages[i].writeTo(System.out);
    }
    folder.close(false);
  }
}





List information about folders

/*
 * @(#)folderlist.java  1.30 05/04/10
 *
 * Copyright 1996-2005 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
 * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
 * SUFFERED BY LICENSEE AS A RESULT OF  OR RELATING TO USE, MODIFICATION
 * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
 * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
 * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that Software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import com.sun.mail.imap.IMAPFolder;
/**
 * Demo app that exercises the Message interfaces. List information about
 * folders.
 * 
 * @author John Mani
 * @author Bill Shannon
 */
public class MainClass {
  static String protocol = null;
  static String host = null;
  static String user = null;
  static String password = null;
  static String url = null;
  static String root = null;
  static String pattern = "%";
  static boolean recursive = false;
  static boolean verbose = false;
  static boolean debug = false;
  public static void main(String argv[]) throws Exception {
    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("-L")) {
        url = argv[++optind];
      } else if (argv[optind].equals("-R")) {
        root = argv[++optind];
      } else if (argv[optind].equals("-r")) {
        recursive = true;
      } else if (argv[optind].equals("-v")) {
        verbose = true;
      } else if (argv[optind].equals("-D")) {
        debug = true;
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        System.out
            .println("Usage: folderlist [-T protocol] [-H host] [-U user] [-P password] [-L url]");
        System.out.println("\t[-R root] [-r] [-v] [-D] [pattern]");
        System.exit(1);
      } else {
        break;
      }
    }
    if (optind < argv.length)
      pattern = argv[optind];
    // Get a Properties object
    Properties props = System.getProperties();
    // Get a Session object
    Session session = Session.getInstance(props, null);
    session.setDebug(debug);
    // Get a Store object
    Store store = null;
    Folder rf = 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();
    }
    // List namespace
    if (root != null)
      rf = store.getFolder(root);
    else
      rf = store.getDefaultFolder();
    dumpFolder(rf, false, "");
    if ((rf.getType() & Folder.HOLDS_FOLDERS) != 0) {
      Folder[] f = rf.list(pattern);
      for (int i = 0; i < f.length; i++)
        dumpFolder(f[i], recursive, "    ");
    }
    store.close();
  }
  static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception {
    System.out.println(tab + "Name:      " + folder.getName());
    System.out.println(tab + "Full Name: " + folder.getFullName());
    System.out.println(tab + "URL:       " + folder.getURLName());
    if (verbose) {
      if (!folder.isSubscribed())
        System.out.println(tab + "Not Subscribed");
      if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
        if (folder.hasNewMessages())
          System.out.println(tab + "Has New Messages");
        System.out.println(tab + "Total Messages:  " + folder.getMessageCount());
        System.out.println(tab + "New Messages:    " + folder.getNewMessageCount());
        System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount());
      }
      if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0)
        System.out.println(tab + "Is Directory");
      /*
       * Demonstrate use of IMAP folder attributes returned by the IMAP LIST
       * response.
       */
      if (folder instanceof IMAPFolder) {
        IMAPFolder f = (IMAPFolder) folder;
        String[] attrs = f.getAttributes();
        if (attrs != null && attrs.length > 0) {
          System.out.println(tab + "IMAP Attributes:");
          for (int i = 0; i < attrs.length; i++)
            System.out.println(tab + "    " + attrs[i]);
        }
      }
    }
    System.out.println();
    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
      if (recurse) {
        Folder[] f = folder.list();
        for (int i = 0; i < f.length; i++)
          dumpFolder(f[i], recurse, tab + "    ");
      }
    }
  }
}





MOVE messages between mailboxes

/*
 * @(#)mover.java 1.9 05/11/17
 *
 * Copyright 1996-2003 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
 * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
 * SUFFERED BY LICENSEE AS A RESULT OF  OR RELATING TO USE, MODIFICATION
 * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
 * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
 * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that Software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
/* MOVE messages between mailboxes */
public class MainClass {
  static String protocol = "imap";
  static String host = null;
  static String user = null;
  static String password = null;
  static String src = null;
  static String dest = null;
  static boolean expunge = false;
  static String url = null;
  public static void main(String argv[]) {
    int start = 1;
    int end = -1;
    int optind;
    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);
    }
  }
}





Search the given folder for messages matching the given criteria

/*
 * @(#)search.java  1.14 03/04/22
 *
 * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
 * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
 * SUFFERED BY LICENSEE AS A RESULT OF  OR RELATING TO USE, MODIFICATION
 * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
 * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
 * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that Software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.search.AndTerm;
import javax.mail.search.ruparisonTerm;
import javax.mail.search.FromStringTerm;
import javax.mail.search.OrTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
// import javax.activation.*;
/*
 * Search the given folder for messages matching the given criteria.
 * 
 * @author John Mani
 */
public class search {
  static String protocol = "imap";
  static String host = null;
  static String user = null;
  static String password = null;
  static String mbox = "INBOX";
  static String url = null;
  static boolean debug = false;
  public static void main(String argv[]) {
    int optind;
    String subject = null;
    String from = null;
    boolean or = false;
    boolean today = false;
    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("-or")) {
        or = 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("-subject")) {
        subject = argv[++optind];
      } else if (argv[optind].equals("-from")) {
        from = argv[++optind];
      } else if (argv[optind].equals("-today")) {
        today = true;
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        System.out.println("Usage: search [-D] [-L url] [-T protocol] [-H host] "
            + "[-U user] [-P password] [-f mailbox] "
            + "[-subject subject] [-from from] [-or] [-today]");
        System.exit(1);
      } else {
        break;
      }
    }
    try {
      if ((subject == null) && (from == null) && !today) {
        System.out.println("Specify either -subject, -from or -today");
        System.exit(1);
      }
      // Get a Properties object
      Properties props = System.getProperties();
      // Get a Session object
      Session session = Session.getInstance(props, null);
      session.setDebug(debug);
      // 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("Cant find default namespace");
        System.exit(1);
      }
      folder = folder.getFolder(mbox);
      if (folder == null) {
        System.out.println("Invalid folder");
        System.exit(1);
      }
      folder.open(Folder.READ_ONLY);
      SearchTerm term = null;
      if (subject != null)
        term = new SubjectTerm(subject);
      if (from != null) {
        FromStringTerm fromTerm = new FromStringTerm(from);
        if (term != null) {
          if (or)
            term = new OrTerm(term, fromTerm);
          else
            term = new AndTerm(term, fromTerm);
        } else
          term = fromTerm;
      }
      if (today) {
        ReceivedDateTerm dateTerm = new ReceivedDateTerm(ComparisonTerm.EQ, new Date());
        if (term != null) {
          if (or)
            term = new OrTerm(term, dateTerm);
          else
            term = new AndTerm(term, dateTerm);
        } else
          term = dateTerm;
      }
      Message[] msgs = folder.search(term);
      System.out.println("FOUND " + msgs.length + " MESSAGES");
      if (msgs.length == 0) // no match
        System.exit(1);
      // Use a suitable FetchProfile
      FetchProfile fp = new FetchProfile();
      fp.add(FetchProfile.Item.ENVELOPE);
      folder.fetch(msgs, fp);
      for (int i = 0; i < msgs.length; i++) {
        System.out.println("--------------------------");
        System.out.println("MESSAGE #" + (i + 1) + ":");
        dumpPart(msgs[i]);
      }
      folder.close(false);
      store.close();
    } catch (Exception ex) {
      System.out.println("Oops, got exception! " + ex.getMessage());
      ex.printStackTrace();
    }
    System.exit(1);
  }
  public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message) {
      Message m = (Message) p;
      Address[] a;
      // FROM
      if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++)
          System.out.println("FROM: " + a[j].toString());
      }
      // TO
      if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++)
          System.out.println("TO: " + a[j].toString());
      }
      // SUBJECT
      System.out.println("SUBJECT: " + m.getSubject());
      // DATE
      Date d = m.getSentDate();
      System.out.println("SendDate: " + (d != null ? d.toLocaleString() : "UNKNOWN"));
      // FLAGS:
      Flags flags = m.getFlags();
      StringBuffer sb = new StringBuffer();
      Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
      boolean first = true;
      for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED)
          s = "\\Answered";
        else if (f == Flags.Flag.DELETED)
          s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT)
          s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED)
          s = "\\Flagged";
        else if (f == Flags.Flag.RECENT)
          s = "\\Recent";
        else if (f == Flags.Flag.SEEN)
          s = "\\Seen";
        else
          continue; // skip it
        if (first)
          first = false;
        else
          sb.append(" ");
        sb.append(s);
      }
      String[] uf = flags.getUserFlags(); // get the user flag strings
      for (int i = 0; i < uf.length; i++) {
        if (first)
          first = false;
        else
          sb.append(" ");
        sb.append(uf[i]);
      }
      System.out.println("FLAGS = " + sb.toString());
    }
    System.out.println("CONTENT-TYPE: " + p.getContentType());
    /*
     * Dump input stream InputStream is = ((MimeMessage)m).getInputStream(); int
     * c; while ((c = is.read()) != -1) System.out.write(c);
     */
    Object o = p.getContent();
    if (o instanceof String) {
      System.out.println("This is a String");
      System.out.println((String) o);
    } else if (o instanceof Multipart) {
      System.out.println("This is a Multipart");
      Multipart mp = (Multipart) o;
      int count = mp.getCount();
      for (int i = 0; i < count; i++)
        dumpPart(mp.getBodyPart(i));
    } else if (o instanceof InputStream) {
      System.out.println("This is just an input stream");
      InputStream is = (InputStream) o;
      int c;
      while ((c = is.read()) != -1)
        System.out.write(c);
    }
  }
}





Show the namespaces supported by a store

/*
 * @(#)namespace.java 1.5 04/02/27
 *
 * Copyright 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
 * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
 * SUFFERED BY LICENSEE AS A RESULT OF  OR RELATING TO USE, MODIFICATION
 * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
 * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
 * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that Software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.FolderNotFoundException;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
/*
 * Demo app that exercises the namespace interfaces. Show the namespaces
 * supported by a store.
 * 
 * @author Bill Shannon
 */
public class MainClass {
  static String protocol;
  static String host = null;
  static String user = null;
  static String password = null;
  static String url = null;
  static int port = -1;
  static boolean debug = false;
  static String suser = "other";
  public static void main(String argv[]) {
    int msgnum = -1;
    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("-D")) {
        debug = true;
      } 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("-u")) {
        suser = argv[++optind];
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        System.out.println("Usage: namespace [-L url] [-T protocol] [-H host] [-p port] [-U user]");
        System.out.println("\t[-P password] [-u other-user] [-D]");
        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);
      // 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, port, user, password);
        else
          store.connect();
      }
      printFolders("Personal", store.getPersonalNamespaces());
      printFolders("User \"" + suser + "\"", store.getUserNamespaces(suser));
      printFolders("Shared", store.getSharedNamespaces());
      store.close();
    } catch (Exception ex) {
      System.out.println("Oops, got exception! " + ex.getMessage());
      ex.printStackTrace();
    }
    System.exit(0);
  }
  private static void printFolders(String name, Folder[] folders) throws MessagingException {
    System.out.println(name + " Namespace:");
    if (folders == null || folders.length == 0) {
      System.out.println("  <none>");
      return;
    }
    for (int i = 0; i < folders.length; i++) {
      String fn = folders[i].getFullName();
      if (fn.length() == 0)
        fn = "<default folder>";
      try {
        System.out.println("  " + fn + ", delimiter \"" + folders[i].getSeparator() + "\"");
        Folder[] fl = folders[i].list();
        if (fl.length > 0) {
          System.out.println("  Subfolders:");
          for (int j = 0; j < fl.length; j++)
            System.out.println("    " + fl[j].getFullName());
        }
      } catch (FolderNotFoundException ex) {
      }
    }
  }
}