Advertisement
Guest User

Untitled

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