Subversion Repositories javautils

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2.  * Copyright 1997-2009 Sun Microsystems, Inc. All Rights Reserved.
  3.  *
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  *
  8.  *   - Redistributions of source code must retain the above copyright
  9.  *     notice, this list of conditions and the following disclaimer.
  10.  *
  11.  *   - Redistributions in binary form must reproduce the above copyright
  12.  *     notice, this list of conditions and the following disclaimer in the
  13.  *     documentation and/or other materials provided with the distribution.
  14.  *
  15.  *   - Neither the name of Sun Microsystems nor the names of its
  16.  *     contributors may be used to endorse or promote products derived
  17.  *     from this software without specific prior written permission.
  18.  *
  19.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  20.  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  21.  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  23.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  24.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  25.  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26.  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27.  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28.  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30.  */
  31.  
  32. import java.util.*;
  33. import java.io.*;
  34. import javax.mail.*;
  35. import javax.mail.event.*;
  36. import javax.mail.internet.*;
  37.  
  38. /*
  39.  * Demo app that exercises the Message interfaces.
  40.  * Show information about and contents of messages.
  41.  *
  42.  * @author John Mani
  43.  * @author Bill Shannon
  44.  */
  45.  
  46. public class msgshow {
  47.  
  48.     static String protocol;
  49.     static String host = null;
  50.     static String user = null;
  51.     static String password = null;
  52.     static String mbox = null;
  53.     static String url = null;
  54.     static int port = -1;
  55.     static boolean verbose = false;
  56.     static boolean debug = false;
  57.     static boolean showStructure = false;
  58.     static boolean showMessage = false;
  59.     static boolean showAlert = false;
  60.     static boolean saveAttachments = false;
  61.     static int attnum = 1;
  62.  
  63.     public static void main(String argv[]) {
  64.         int msgnum = -1;
  65.         int optind;
  66.         InputStream msgStream = System.in;
  67.  
  68.         for (optind = 0; optind < argv.length; optind++) {
  69.             if (argv[optind].equals("-T")) {
  70.                 protocol = argv[++optind];
  71.             } else if (argv[optind].equals("-H")) {
  72.                 host = argv[++optind];
  73.             } else if (argv[optind].equals("-U")) {
  74.                 user = argv[++optind];
  75.             } else if (argv[optind].equals("-P")) {
  76.                 password = argv[++optind];
  77.             } else if (argv[optind].equals("-v")) {
  78.                 verbose = true;
  79.             } else if (argv[optind].equals("-D")) {
  80.                 debug = true;
  81.             } else if (argv[optind].equals("-f")) {
  82.                 mbox = argv[++optind];
  83.             } else if (argv[optind].equals("-L")) {
  84.                 url = argv[++optind];
  85.             } else if (argv[optind].equals("-p")) {
  86.                 port = Integer.parseInt(argv[++optind]);
  87.             } else if (argv[optind].equals("-s")) {
  88.                 showStructure = true;
  89.             } else if (argv[optind].equals("-S")) {
  90.                 saveAttachments = true;
  91.             } else if (argv[optind].equals("-m")) {
  92.                 showMessage = true;
  93.             } else if (argv[optind].equals("-a")) {
  94.                 showAlert = true;
  95.             } else if (argv[optind].equals("--")) {
  96.                 optind++;
  97.                 break;
  98.             } else if (argv[optind].startsWith("-")) {
  99.                 System.out.println(
  100. "Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
  101.                 System.out.println(
  102. "\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
  103.                 System.out.println(
  104. "or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
  105.                 System.exit(1);
  106.             } else {
  107.                 break;
  108.             }
  109.         }
  110.  
  111.         try {
  112.             if (optind < argv.length)
  113.                  msgnum = Integer.parseInt(argv[optind]);
  114.  
  115.             // Get a Properties object
  116.             Properties props = System.getProperties();
  117.  
  118.             // Get a Session object
  119.             Session session = Session.getInstance(props, null);
  120.             session.setDebug(debug);
  121.  
  122.             if (showMessage) {
  123.                 MimeMessage msg;
  124.                 if (mbox != null)
  125.                     msg = new MimeMessage(session,
  126.                         new BufferedInputStream(new FileInputStream(mbox)));
  127.                 else
  128.                     msg = new MimeMessage(session, msgStream);
  129.                 dumpPart(msg);
  130.                 System.exit(0);
  131.             }
  132.  
  133.             // Get a Store object
  134.             Store store = null;
  135.             if (url != null) {
  136.                 URLName urln = new URLName(url);
  137.                 store = session.getStore(urln);
  138.                 if (showAlert) {
  139.                     store.addStoreListener(new StoreListener() {
  140.                         public void notification(StoreEvent e) {
  141.                             String s;
  142.                             if (e.getMessageType() == StoreEvent.ALERT)
  143.                                 s = "ALERT: ";
  144.                             else
  145.                                 s = "NOTICE: ";
  146.                             System.out.println(s + e.getMessage());
  147.                         }
  148.                     });
  149.                 }
  150.                 store.connect();
  151.             } else {
  152.                 if (protocol != null)          
  153.                     store = session.getStore(protocol);
  154.                 else
  155.                     store = session.getStore();
  156.  
  157.                 // Connect
  158.                 if (host != null || user != null || password != null)
  159.                     store.connect(host, port, user, password);
  160.                 else
  161.                     store.connect();
  162.             }
  163.            
  164.  
  165.             // Open the Folder
  166.  
  167.             Folder folder = store.getDefaultFolder();
  168.             if (folder == null) {
  169.                 System.out.println("No default folder");
  170.                 System.exit(1);
  171.             }
  172.  
  173.             if (mbox == null)
  174.                 mbox = "INBOX";
  175.             folder = folder.getFolder(mbox);
  176.             if (folder == null) {
  177.                 System.out.println("Invalid folder");
  178.                 System.exit(1);
  179.             }
  180.  
  181.             // try to open read/write and if that fails try read-only
  182.             try {
  183.                 folder.open(Folder.READ_WRITE);
  184.             } catch (MessagingException ex) {
  185.                 folder.open(Folder.READ_ONLY);
  186.             }
  187.             int totalMessages = folder.getMessageCount();
  188.  
  189.             if (totalMessages == 0) {
  190.                 System.out.println("Empty folder");
  191.                 folder.close(false);
  192.                 store.close();
  193.                 System.exit(1);
  194.             }
  195.  
  196.             if (verbose) {
  197.                 int newMessages = folder.getNewMessageCount();
  198.                 System.out.println("Total messages = " + totalMessages);
  199.                 System.out.println("New messages = " + newMessages);
  200.                 System.out.println("-------------------------------");
  201.             }
  202.  
  203.             if (msgnum == -1) {
  204.                 // Attributes & Flags for all messages ..
  205.                 Message[] msgs = folder.getMessages();
  206.  
  207.                 // Use a suitable FetchProfile
  208.                 FetchProfile fp = new FetchProfile();
  209.                 fp.add(FetchProfile.Item.ENVELOPE);
  210.                 fp.add(FetchProfile.Item.FLAGS);
  211.                 fp.add("X-Mailer");
  212.                 folder.fetch(msgs, fp);
  213.  
  214.                 for (int i = 0; i < msgs.length; i++) {
  215.                     System.out.println("--------------------------");
  216.                     System.out.println("MESSAGE #" + (i + 1) + ":");
  217.                     dumpEnvelope(msgs[i]);
  218.                     // dumpPart(msgs[i]);
  219.                 }
  220.             } else {
  221.                 System.out.println("Getting message number: " + msgnum);
  222.                 Message m = null;
  223.                
  224.                 try {
  225.                     m = folder.getMessage(msgnum);
  226.                     dumpPart(m);
  227.                 } catch (IndexOutOfBoundsException iex) {
  228.                     System.out.println("Message number out of range");
  229.                 }
  230.             }
  231.  
  232.             folder.close(false);
  233.             store.close();
  234.         } catch (Exception ex) {
  235.             System.out.println("Oops, got exception! " + ex.getMessage());
  236.             ex.printStackTrace();
  237.             System.exit(1);
  238.         }
  239.         System.exit(0);
  240.     }
  241.  
  242.     public static void dumpPart(Part p) throws Exception {
  243.         if (p instanceof Message)
  244.             dumpEnvelope((Message)p);
  245.  
  246.         /** Dump input stream ..
  247.  
  248.         InputStream is = p.getInputStream();
  249.         // If "is" is not already buffered, wrap a BufferedInputStream
  250.         // around it.
  251.         if (!(is instanceof BufferedInputStream))
  252.             is = new BufferedInputStream(is);
  253.         int c;
  254.         while ((c = is.read()) != -1)
  255.             System.out.write(c);
  256.  
  257.         **/
  258.  
  259.         String ct = p.getContentType();
  260.         try {
  261.             pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
  262.         } catch (ParseException pex) {
  263.             pr("BAD CONTENT-TYPE: " + ct);
  264.         }
  265.         String filename = p.getFileName();
  266.         if (filename != null)
  267.             pr("FILENAME: " + filename);
  268.  
  269.         /*
  270.          * Using isMimeType to determine the content type avoids
  271.          * fetching the actual content data until we need it.
  272.          */
  273.         if (p.isMimeType("text/plain")) {
  274.             pr("This is plain text");
  275.             pr("---------------------------");
  276.             if (!showStructure && !saveAttachments)
  277.                 System.out.println((String)p.getContent());
  278.         } else if (p.isMimeType("multipart/*")) {
  279.             pr("This is a Multipart");
  280.             pr("---------------------------");
  281.             Multipart mp = (Multipart)p.getContent();
  282.             level++;
  283.             int count = mp.getCount();
  284.             for (int i = 0; i < count; i++)
  285.                 dumpPart(mp.getBodyPart(i));
  286.             level--;
  287.         } else if (p.isMimeType("message/rfc822")) {
  288.             pr("This is a Nested Message");
  289.             pr("---------------------------");
  290.             level++;
  291.             dumpPart((Part)p.getContent());
  292.             level--;
  293.         } else {
  294.             if (!showStructure && !saveAttachments) {
  295.                 /*
  296.                  * If we actually want to see the data, and it's not a
  297.                  * MIME type we know, fetch it and check its Java type.
  298.                  */
  299.                 Object o = p.getContent();
  300.                 if (o instanceof String) {
  301.                     pr("This is a string");
  302.                     pr("---------------------------");
  303.                     System.out.println((String)o);
  304.                 } else if (o instanceof InputStream) {
  305.                     pr("This is just an input stream");
  306.                     pr("---------------------------");
  307.                     InputStream is = (InputStream)o;
  308.                     int c;
  309.                     while ((c = is.read()) != -1)
  310.                         System.out.write(c);
  311.                 } else {
  312.                     pr("This is an unknown type");
  313.                     pr("---------------------------");
  314.                     pr(o.toString());
  315.                 }
  316.             } else {
  317.                 // just a separator
  318.                 pr("---------------------------");
  319.             }
  320.         }
  321.  
  322.         /*
  323.          * If we're saving attachments, write out anything that
  324.          * looks like an attachment into an appropriately named
  325.          * file.  Don't overwrite existing files to prevent
  326.          * mistakes.
  327.          */
  328.         if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
  329.             String disp = p.getDisposition();
  330.             // many mailers don't include a Content-Disposition
  331.             if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
  332.                 if (filename == null)
  333.                     filename = "Attachment" + attnum++;
  334.                 pr("Saving attachment to file " + filename);
  335.                 try {
  336.                     File f = new File(filename);
  337.                     if (f.exists())
  338.                         // XXX - could try a series of names
  339.                         throw new IOException("file exists");
  340.                     ((MimeBodyPart)p).saveFile(f);
  341.                 } catch (IOException ex) {
  342.                     pr("Failed to save attachment: " + ex);
  343.                 }
  344.                 pr("---------------------------");
  345.             }
  346.         }
  347.     }
  348.  
  349.     public static void dumpEnvelope(Message m) throws Exception {
  350.         pr("This is the message envelope");
  351.         pr("---------------------------");
  352.         Address[] a;
  353.         // FROM
  354.         if ((a = m.getFrom()) != null) {
  355.             for (int j = 0; j < a.length; j++)
  356.                 pr("FROM: " + a[j].toString());
  357.         }
  358.  
  359.         // REPLY TO
  360.         if ((a = m.getReplyTo()) != null) {
  361.             for (int j = 0; j < a.length; j++)
  362.                 pr("REPLY TO: " + a[j].toString());
  363.         }
  364.  
  365.         // TO
  366.         if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
  367.             for (int j = 0; j < a.length; j++) {
  368.                 pr("TO: " + a[j].toString());
  369.                 InternetAddress ia = (InternetAddress)a[j];
  370.                 if (ia.isGroup()) {
  371.                     InternetAddress[] aa = ia.getGroup(false);
  372.                     for (int k = 0; k < aa.length; k++)
  373.                         pr("  GROUP: " + aa[k].toString());
  374.                 }
  375.             }
  376.         }
  377.  
  378.         // SUBJECT
  379.         pr("SUBJECT: " + m.getSubject());
  380.  
  381.         // DATE
  382.         Date d = m.getSentDate();
  383.         pr("SendDate: " +
  384.             (d != null ? d.toString() : "UNKNOWN"));
  385.  
  386.         // FLAGS
  387.         Flags flags = m.getFlags();
  388.         StringBuffer sb = new StringBuffer();
  389.         Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
  390.  
  391.         boolean first = true;
  392.         for (int i = 0; i < sf.length; i++) {
  393.             String s;
  394.             Flags.Flag f = sf[i];
  395.             if (f == Flags.Flag.ANSWERED)
  396.                 s = "\\Answered";
  397.             else if (f == Flags.Flag.DELETED)
  398.                 s = "\\Deleted";
  399.             else if (f == Flags.Flag.DRAFT)
  400.                 s = "\\Draft";
  401.             else if (f == Flags.Flag.FLAGGED)
  402.                 s = "\\Flagged";
  403.             else if (f == Flags.Flag.RECENT)
  404.                 s = "\\Recent";
  405.             else if (f == Flags.Flag.SEEN)
  406.                 s = "\\Seen";
  407.             else
  408.                 continue;       // skip it
  409.             if (first)
  410.                 first = false;
  411.             else
  412.                 sb.append(' ');
  413.             sb.append(s);
  414.         }
  415.  
  416.         String[] uf = flags.getUserFlags(); // get the user flag strings
  417.         for (int i = 0; i < uf.length; i++) {
  418.             if (first)
  419.                 first = false;
  420.             else
  421.                 sb.append(' ');
  422.             sb.append(uf[i]);
  423.         }
  424.         pr("FLAGS: " + sb.toString());
  425.  
  426.         // X-MAILER
  427.         String[] hdrs = m.getHeader("X-Mailer");
  428.         if (hdrs != null)
  429.             pr("X-Mailer: " + hdrs[0]);
  430.         else
  431.             pr("X-Mailer NOT available");
  432.     }
  433.  
  434.     static String indentStr = "                                               ";
  435.     static int level = 0;
  436.  
  437.     /**
  438.      * Print a, possibly indented, string.
  439.      */
  440.     public static void pr(String s) {
  441.         if (showStructure)
  442.             System.out.print(indentStr.substring(0, level * 2));
  443.         System.out.println(s);
  444.     }
  445. }
  446.