/*
 * @(#)msgshow.java 1.24 00/10/14
 *
 * Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * 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 SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING 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.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;/*
 * Demo app that exercises the Message interfaces.
 * Show information about and contents of messages.
 *
 * @author John Mani
 * @author Bill Shannon
 */public class msgshow {    static String protocol;
    static String host = null;
    static String user = null;
    static String password = null;
    static String mbox = "INBOX";
    static String url = null;
    static int port = -1;
    static boolean verbose = false;
    static boolean debug = false;
    static boolean showStructure = false;
    static boolean showMessage = false;    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("-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("-m")) {
showMessage = 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]");
System.out.println(
"or     msgshow -m [-v] [-D] [-s] < msg");
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.getDefaultInstance(props, null);
    session.setDebug(debug);     if (showMessage) {
MimeMessage msg = new MimeMessage(session, System.in);
dumpPart(msg);
System.exit(0);
    }     // 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();
    }
         // 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 == 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);
    }    public static void dumpPart(Part p) throws Exception {
if (p instanceof Message)
    dumpEnvelope((Message)p); /** Dump input stream ..  InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
    is = new BufferedInputStream(is);
int c;
while ((c = is.read()) != -1)
    System.out.write(c); **/ pr("CONTENT-TYPE: " + p.getContentType());
String filename = p.getFileName();
if (filename != null)
    pr("FILENAME: " + filename); /*
 * Using isMimeType to determine the content type avoids
 * fetching the actual content data until we need it.
 */
if (p.isMimeType("text/plain")) {
    pr("This is plain text");
    pr("---------------------------");
    if (!showStructure)
System.out.println((String)p.getContent());
} else if (p.isMimeType("multipart/*")) {
    pr("This is a Multipart");
    pr("---------------------------");
    Multipart mp = (Multipart)p.getContent();
    level++;
    int count = mp.getCount();
    for (int i = 0; i < count; i++)
dumpPart(mp.getBodyPart(i));
    level--;
} else if (p.isMimeType("message/rfc822")) {
    pr("This is a Nested Message");
    pr("---------------------------");
    level++;
    dumpPart((Part)p.getContent());
    level--;
} else if (!showStructure) {
    /*
     * If we actually want to see the data, and it's not a
     * MIME type we know, fetch it and check its Java type.
     */
    Object o = p.getContent();
    if (o instanceof String) {
pr("This is a string");
pr("---------------------------");
System.out.println((String)o);
    } else if (o instanceof InputStream) {
pr("This is just an input stream");
pr("---------------------------");
InputStream is = (InputStream)o;
int c;
while ((c = is.read()) != -1)
    System.out.write(c);
    } else {
pr("This is an unknown type");
pr("---------------------------");
pr(o.toString());
    }
} else {
    pr("This is an unknown type");
    pr("---------------------------");
}
    }    public static void dumpEnvelope(Message m) throws Exception {
pr("This is the message envelope");
pr("---------------------------");
Address[] a;
// FROM 
if ((a = m.getFrom()) != null) {
    for (int j = 0; j < a.length; j++)
pr("FROM: " + a[j].toString());
} // TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
    for (int j = 0; j < a.length; j++)
pr("TO: " + a[j].toString());
} // SUBJECT
pr("SUBJECT: " + m.getSubject()); // DATE
Date d = m.getSentDate();
pr("SendDate: " +
    (d != null ? d.toString() : "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]);
}
pr("FLAGS: " + sb.toString()); // X-MAILER
String[] hdrs = m.getHeader("X-Mailer");
if (hdrs != null)
    pr("X-Mailer: " + hdrs[0]);
else
    pr("X-Mailer NOT available");
    }    static String indentStr = "                                               ";
    static int level = 0;    /**
     * Print a, possibly indented, string.
     */
    public static void pr(String s) {
if (showStructure)
    System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
    }
}

解决方案 »

  1.   

    上面那个我收不到邮件呀,具体的参数要如何加入,请: skyyoung(路人甲) 指教
      

  2.   

    README for the demo programs in this directory
    ==============================================These demo programs illustrate how to use the JavaMail API to
    perform a number of common email functions.  Note these these
    programs are not intended to be examples of good user interfaces,
    or good command line interfaces.  No one is expected to actually
    *use* these programs for anything real.  Rather, their value is
    in the source code.  Don't look at their command line arguments
    or user interface to figure out what JavaMail can do, look at
    their source code.  We strongly recommend that you read the
    source code and understand what these programs are doing before
    running them.All of these programs are simple command line tools with a UNIX
    style interface.  On Windows you'll need to run them in an MS-DOS
    window.  We apologize in advance for the inconsistency in how these
    programs accept options.  There are generally two styles.  The very
    simple style (e.g., as used by copier.java) requires a fixed number
    of arguments in a fixed order.  Others (e.g., folderlist.java) take
    UNIX-style options, many of which are optional, and which may appear
    in any order.  The following notes should help you figure it out,
    but if in doubt, read the source code.- copier.java This program copies the specified messages from one folder to
    another. Both folders must belong to the same store.  Usage:
    java copier <urlname> <src> <dest> <start> <end>  Arguments (in order):  <urlname> : URL of the Store. The URL should include
      the password as well (if needed).
      Example: "imap://john:[email protected]"  <src> : source folder
      <dest> : destination folder
      <start> : start message number
      <end> : end message number
    - folderlist.java This program lists information about the folders in a Store.   Usage:
    java folderlist -L <url> -T <protocol> -H <host> -U <user> -P <passwd>
       [-R <root>] [-r] [-v] [-D] <pattern>   Options:   -L <url> : URL of the Store. The URL should include
      the password as well (if needed).
      Example: "imap://john:[email protected]"
       -T <protocol> : store protocol (Ex: "imap")
       -H <host> : hostname of store.
       -U <user> : username (if needed)
       -P <passwd> : password (if needed)
       -R <root> : root of the folder hierarchy. This is optional. If
      not present, listing starts from the default folder.
       -r : list recursively - folder and all subfolders.
       -v : verbose - show more info about each folder.
       -D : Turn on session debugging
       <pattern> : folders that match this pattern are listed. Use "*"
      as wildcard to match everything.
    - monitor.java Illustrates how to monitor a folder for interesting events,
    like new mail arrival.   Usage:
    java monitor <host> <user> <password> <mbox> <freq>   Arguments (in order):   <host> : hostname of store.
       <user> : username (if needed)
       <passwd> : password (if needed)
       <mbox> : folder to monitor
       <freq> : frequency of monitoring
    - mover.java Moves messages between folders.  The folders must belong to the
    same store.   Usage:
    java mover -T <protocol> -H <host> -U <user> -P <passwd> [-v]
    -s <src> -d <dest> [-x] <start> <end>   Options:   -T <protocol> : store protocol (Ex: "imap")
       -H <host> : hostname of store.
       -U <user> : username (if needed)
       -P <passwd> : password (if needed)
       -s <src> : source folder
       -d <dest> : destination folder
       -v : Optional verbose option
       -x : Optional expunge option, to expunge the deleted
      messages from src   Arguments (in order):   <start> : start message number
       <end> : end message number
    - msgmultisendsample.java Demonstrates how to construct and send a multipart message.   Usage:
    java msgmultisendsample <to> <from> <smtphost> true|false   Arguments (in order):   <to> : Recipient address
       <from> : Sender address
       <smtphost> : name of SMTP server
       true|false : "true" to turn on session debugging, "false" otherwise
    - msgsend.java Send a simple text message. Optionally saves a copy
    of the outgoing message in a folder (record-folder). Most parameters to this program are optional. When
    the program is run, it interactively asks for
    the "To" and "Subject" fields if not already available.
    Then the program expects the body of the message.
    After you type in the body, hit Ctrl-D on Unix
    systems or Ctrl-Z on Windows systems to send
    the message.   Usage:
    java msgsend -L <store-url> -T <protocol> -H <host> -U <user>
    -P <passwd> -s <subject> -o <from> -c <cc> -b <bcc>
    -f <record> -M <smtphost> [-d] <to>   Options:   -L <store-url> : URL of the store for the record-folder
       -T <protocol> : If <store-url> is not present, this indicates
      the store protocol for the record-folder.
       -H <host> : If <store-url> is not present, this indicates
      the hostname for the record-folder.
       -U <user> : If <store-url> is not present, this indicates
      the username for the record-folder.
       -P <passwd> : If <store-url> is not present, this indicates
      the password for the record-folder.
       -f <record> : name of record-folder.
       -M <smtphost> : Host name of SMTP server.  Defaults to "localhost"
      which often works on UNIX but rarely on Windows.
       -s <subject> : Subject of message to be sent
       -o <from> : From address of message to be sent
       -c <cc> : Cc address of message to be sent
       -b <bcc> : Bcc address of message to be sent
       -d : Turn on session debugging.   Argument:   <to> : To address of message to be sent
    - msgsendsample.java Demonstrates how to construct and send a simple text message.   Usage:
    java msgsendsample <to> <from> <smtphost> true|false   Arguments (in order):   <to> : Recipient address
       <from> : Sender address
       <smtphost> : name of SMTP server
       true|false : "true" to turn on session debugging, "false" otherwise
    - msgshow.java Displays message(s) from a folder or from stdin.   Usage:
    java msgshow -L <url> -T <protocol> -H <host> -p <port>
    -U <user> -P <password> -f <mailbox> [-D] [-s] [-v] [msgnum]
    java msgshow -m [-D] [-s] [-v]   Options:   -L <url> : URL of the Store. The URL should include
      the password as well (if needed).
      Example: "imap://john:[email protected]"
       -T <protocol> : If <url> is not present, this indicates
      the store protocol
       -H <host> : If <url> is not present, this indicates
      the hostname
       -p <port> : If <url> is not present, this indicates
      the port number (usually not needed)
       -U <user> : If <url> is not present, this indicates
      the username
       -P <passwd> : If <url> is not present, this indicates
      the password
       -f <mailbox> : Folder to open
       -m : Read message from standard input
       -D : Turn on session debugging
       -s : Show the structure of the message, but not the contents
       -v : Verbose mode - show total messages and number of new messages   Argument:   <msgnum> : the message to be displayed. If this
         parameter is not present, all messages in the
      folder are displayed.
    - namespace.java Displays the namespaces supported by a store.   Usage:
    java namespace -L <url> -T <protocol> -H <host> -p <port>
    -U <user> -P <password> [-D]   Options:   -L <url> : URL of the Store. The URL should include
      the password as well (if needed).
      Example: "imap://john:[email protected]"
       -T <protocol> : If <url> is not present, this indicates
      the store protocol
       -H <host> : If <url> is not present, this indicates
      the hostname
       -p <port> : If <url> is not present, this indicates
      the port number (usually not needed)
       -U <user> : If <url> is not present, this indicates
      the username
       -P <passwd> : If <url> is not present, this indicates
      the password
       -D : Turn on session debugging
    - populate.java Copies an entire folder hierarchy from one message store to
    another.   Usage:
    java populate -s <src-url> -d <dest-url> -D -f   Options:   -s <src-url> : URL of source folder
       -d <dest-url> : URL of destination folder
       -D : Turn on session debugging
       -f : force the copy to occur even if the destination
      folder already exists
       -S : skip folders named "SCCS"
       -c : clear out old folders before copying messages
    - registry.java Demonstrates how to query the JavaMail "registry" for providers,
    set default providers, etc.   Usage:
    java registry
    - search.java Search the given folder for messages matching the
    given criteria.  Illustrates the use of the
    javax.mail.search package.   Usage:
    java search -L <url> -T <prot> -H <host> -U <user> -P <passwd>
    -f <folder> -subject <subject> -from <from>
    -today -or   Options:   -L <url> : URL of the store
       -T <protocol> : If <url> is not present, this indicates
      the store protocol
       -H <host> : If <url> is not present, this indicates
      the hostname
       -U <user> : If <url> is not present, this indicates
      the username
       -P <passwd> : If <url> is not present, this indicates
      the password
       -f <folder> : folder to search   -or : If this flag is present, the search will
      return messages that match any one of the
      below criteria. Else the search will only
      return messages that match all the criteria   -subject <subject> : search for messages containing this string
      as the Subject
       -from <from> : search for messages containing this string
      as the From address
       -today : search for messages received today
    - sendfile.java Send the specified file to the given address.  The file
    is sent as an attachment.  An SMTP server must be available.   Usage:
    java sendfile <to> <from> <smtphost> <file> true|false   Arguments (in order):   <to> : Recipient address
       <from> : Sender address
       <smtphost> : name of SMTP server
       <file> : name of file to be sent
       true|false : "true" to turn on session debugging, "false" otherwise
    - sendhtml.java The sendhtml program works like the msgsend program, taking
    the same options and input, but the text collected from the
    user is sent as type "text/html" instead of "text/plain". This program is a good example of how to send arbitrary
    string data as any arbitrary MIME type.
    - transport.java Illustrates how to use an explicit Transport object, how to
    handle transport exceptions, and how to handle transport events.   Usage:
    java transport <to> <from> <smtphost> <file> true|false   Arguments (in order):   <to> : Recipient address
       <from> : Sender address
       <smtphost> : name of SMTP server
       <file> : name of file to be sent
       true|false : "true" to turn on session debugging, "false" otherwise
    - uidmsgshow.java The uidmsgshow program works like the msgshow program, taking
    the same options, except instead of using message numbers, it
    uses message UID's.  This will typically only work with IMAP
    message stores.
      

  3.   

    是的。好象从网上复制过来的。还有,有没有可以直接读取.eml文件来查看邮件内容的java程序啊?我想借用这个java程序来替代outlook express。
      

  4.   

    http://www.csdn.net/expert/topic/675/675456.xml?temp=.9638941
    http://www.csdn.net/expert/topic/675/675462.xml?temp=.5193292
    http://www.csdn.net/expert/topic/675/675467.xml?temp=.3912165
    http://www.csdn.net/expert/topic/675/675469.xml?temp=.3861505