KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > msgshow


1 /*
2  * @(#)msgshow.java 1.30 03/04/22
3  *
4  * Copyright 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * - Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * - Redistribution in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in the
15  * documentation and/or other materials provided with the distribution.
16  *
17  * Neither the name of Sun Microsystems, Inc. or the names of contributors
18  * may be used to endorse or promote products derived from this software
19  * without specific prior written permission.
20  *
21  * This software is provided "AS IS," without a warranty of any kind. ALL
22  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
23  * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
24  * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
25  * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
26  * SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION
27  * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
28  * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
29  * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
30  * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
31  * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
32  * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
33  *
34  * You acknowledge that Software is not designed, licensed or intended
35  * for use in the design, construction, operation or maintenance of any
36  * nuclear facility.
37  */

38
39 import java.util.*;
40 import java.io.*;
41 import javax.mail.*;
42 import javax.mail.event.*;
43 import javax.mail.internet.*;
44 import javax.activation.*;
45
46 /*
47  * Demo app that exercises the Message interfaces.
48  * Show information about and contents of messages.
49  *
50  * @author John Mani
51  * @author Bill Shannon
52  */

53
54 public class msgshow {
55
56     static String JavaDoc protocol;
57     static String JavaDoc host = null;
58     static String JavaDoc user = null;
59     static String JavaDoc password = null;
60     static String JavaDoc mbox = "INBOX";
61     static String JavaDoc url = null;
62     static int port = -1;
63     static boolean verbose = false;
64     static boolean debug = false;
65     static boolean showStructure = false;
66     static boolean showMessage = false;
67     static boolean showAlert = false;
68     static boolean saveAttachments = false;
69     static int attnum = 1;
70
71     public static void main(String JavaDoc argv[]) {
72     int msgnum = -1;
73     int optind;
74     InputStream msgStream = System.in;
75
76     for (optind = 0; optind < argv.length; optind++) {
77         if (argv[optind].equals("-T")) {
78         protocol = argv[++optind];
79         } else if (argv[optind].equals("-H")) {
80         host = argv[++optind];
81         } else if (argv[optind].equals("-U")) {
82         user = argv[++optind];
83         } else if (argv[optind].equals("-P")) {
84         password = argv[++optind];
85         } else if (argv[optind].equals("-v")) {
86         verbose = true;
87         } else if (argv[optind].equals("-D")) {
88         debug = true;
89         } else if (argv[optind].equals("-f")) {
90         mbox = argv[++optind];
91         } else if (argv[optind].equals("-L")) {
92         url = argv[++optind];
93         } else if (argv[optind].equals("-p")) {
94         port = Integer.parseInt(argv[++optind]);
95         } else if (argv[optind].equals("-s")) {
96         showStructure = true;
97         } else if (argv[optind].equals("-S")) {
98         saveAttachments = true;
99         } else if (argv[optind].equals("-m")) {
100         showMessage = true;
101         } else if (argv[optind].equals("-a")) {
102         showAlert = true;
103         } else if (argv[optind].equals("--")) {
104         optind++;
105         break;
106         } else if (argv[optind].startsWith("-")) {
107         System.out.println(
108 "Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
109         System.out.println(
110 "\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
111         System.out.println(
112 "or msgshow -m [-v] [-D] [-s] [-S] < msg");
113         System.exit(1);
114         } else {
115         break;
116         }
117     }
118
119         try {
120         if (optind < argv.length)
121              msgnum = Integer.parseInt(argv[optind]);
122
123         // Get a Properties object
124
Properties props = System.getProperties();
125
126         // Get a Session object
127
Session session = Session.getInstance(props, null);
128         session.setDebug(debug);
129
130         if (showMessage) {
131         MimeMessage msg = new MimeMessage(session, msgStream);
132         dumpPart(msg);
133         System.exit(0);
134         }
135
136         // Get a Store object
137
Store store = null;
138         if (url != null) {
139         URLName urln = new URLName(url);
140         store = session.getStore(urln);
141         if (showAlert) {
142             store.addStoreListener(new StoreListener() {
143             public void notification(StoreEvent e) {
144                 String JavaDoc s;
145                 if (e.getMessageType() == StoreEvent.ALERT)
146                 s = "ALERT: ";
147                 else
148                 s = "NOTICE: ";
149                 System.out.println(s + e.getMessage());
150             }
151             });
152         }
153         store.connect();
154         } else {
155         if (protocol != null)
156             store = session.getStore(protocol);
157         else
158             store = session.getStore();
159
160         // Connect
161
if (host != null || user != null || password != null)
162             store.connect(host, port, user, password);
163         else
164             store.connect();
165         }
166         
167
168         // Open the Folder
169

170         Folder folder = store.getDefaultFolder();
171         if (folder == null) {
172             System.out.println("No default folder");
173             System.exit(1);
174         }
175
176         folder = folder.getFolder(mbox);
177         if (folder == null) {
178             System.out.println("Invalid folder");
179             System.exit(1);
180         }
181
182         // try to open read/write and if that fails try read-only
183
try {
184         folder.open(Folder.READ_WRITE);
185         } catch (MessagingException ex) {
186         folder.open(Folder.READ_ONLY);
187         }
188         int totalMessages = folder.getMessageCount();
189
190         if (totalMessages == 0) {
191         System.out.println("Empty folder");
192         folder.close(false);
193         store.close();
194         System.exit(1);
195         }
196
197         if (verbose) {
198         int newMessages = folder.getNewMessageCount();
199         System.out.println("Total messages = " + totalMessages);
200         System.out.println("New messages = " + newMessages);
201         System.out.println("-------------------------------");
202         }
203
204         if (msgnum == -1) {
205         // Attributes & Flags for all messages ..
206
Message[] msgs = folder.getMessages();
207
208         // Use a suitable FetchProfile
209
FetchProfile fp = new FetchProfile();
210         fp.add(FetchProfile.Item.ENVELOPE);
211         fp.add(FetchProfile.Item.FLAGS);
212         fp.add("X-Mailer");
213         folder.fetch(msgs, fp);
214
215         for (int i = 0; i < msgs.length; i++) {
216             System.out.println("--------------------------");
217             System.out.println("MESSAGE #" + (i + 1) + ":");
218             dumpEnvelope(msgs[i]);
219             // dumpPart(msgs[i]);
220
}
221         } else {
222         System.out.println("Getting message number: " + msgnum);
223         Message m = null;
224         
225         try {
226             m = folder.getMessage(msgnum);
227             dumpPart(m);
228         } catch (IndexOutOfBoundsException JavaDoc iex) {
229             System.out.println("Message number out of range");
230         }
231         }
232
233         folder.close(false);
234         store.close();
235     } catch (Exception JavaDoc ex) {
236         System.out.println("Oops, got exception! " + ex.getMessage());
237         ex.printStackTrace();
238         System.exit(1);
239     }
240     System.exit(0);
241     }
242
243     public static void dumpPart(Part p) throws Exception JavaDoc {
244     if (p instanceof Message)
245         dumpEnvelope((Message)p);
246
247     /** Dump input stream ..
248
249     InputStream is = p.getInputStream();
250     // If "is" is not already buffered, wrap a BufferedInputStream
251     // around it.
252     if (!(is instanceof BufferedInputStream))
253         is = new BufferedInputStream(is);
254     int c;
255     while ((c = is.read()) != -1)
256         System.out.write(c);
257
258     **/

259
260     String JavaDoc ct = p.getContentType();
261     try {
262         pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
263     } catch (ParseException pex) {
264         pr("BAD CONTENT-TYPE: " + ct);
265     }
266     String JavaDoc filename = p.getFileName();
267     if (filename != null)
268         pr("FILENAME: " + filename);
269
270     /*
271      * Using isMimeType to determine the content type avoids
272      * fetching the actual content data until we need it.
273      */

274     if (p.isMimeType("text/plain")) {
275         pr("This is plain text");
276         pr("---------------------------");
277         if (!showStructure && !saveAttachments)
278         System.out.println((String JavaDoc)p.getContent());
279     } else if (p.isMimeType("multipart/*")) {
280         pr("This is a Multipart");
281         pr("---------------------------");
282         Multipart mp = (Multipart)p.getContent();
283         level++;
284         int count = mp.getCount();
285         for (int i = 0; i < count; i++)
286         dumpPart(mp.getBodyPart(i));
287         level--;
288     } else if (p.isMimeType("message/rfc822")) {
289         pr("This is a Nested Message");
290         pr("---------------------------");
291         level++;
292         dumpPart((Part)p.getContent());
293         level--;
294     } else {
295         if (!showStructure && !saveAttachments) {
296         /*
297          * If we actually want to see the data, and it's not a
298          * MIME type we know, fetch it and check its Java type.
299          */

300         Object JavaDoc o = p.getContent();
301         if (o instanceof String JavaDoc) {
302             pr("This is a string");
303             pr("---------------------------");
304             System.out.println((String JavaDoc)o);
305         } else if (o instanceof InputStream) {
306             pr("This is just an input stream");
307             pr("---------------------------");
308             InputStream is = (InputStream)o;
309             int c;
310             while ((c = is.read()) != -1)
311             System.out.write(c);
312         } else {
313             pr("This is an unknown type");
314             pr("---------------------------");
315             pr(o.toString());
316         }
317         } else {
318         // just a separator
319
pr("---------------------------");
320         }
321     }
322
323     /*
324      * If we're saving attachments, write out anything that
325      * looks like an attachment into an appropriately named
326      * file. Don't overwrite existing files to prevent
327      * mistakes.
328      */

329     if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
330         String JavaDoc disp = p.getDisposition();
331         // many mailers don't include a Content-Disposition
332
if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
333         if (filename == null)
334             filename = "Attachment" + attnum++;
335         pr("Saving attachment to file " + filename);
336         try {
337             File f = new File(filename);
338             if (f.exists())
339             // XXX - could try a series of names
340
throw new IOException("file exists");
341             OutputStream os =
342             new BufferedOutputStream(new FileOutputStream(f));
343             InputStream is = p.getInputStream();
344             int c;
345             while ((c = is.read()) != -1)
346             os.write(c);
347             os.close();
348         } catch (IOException ex) {
349             pr("Failed to save attachment: " + ex);
350         }
351         pr("---------------------------");
352         }
353     }
354     }
355
356     public static void dumpEnvelope(Message m) throws Exception JavaDoc {
357     pr("This is the message envelope");
358     pr("---------------------------");
359     Address[] a;
360     // FROM
361
if ((a = m.getFrom()) != null) {
362         for (int j = 0; j < a.length; j++)
363         pr("FROM: " + a[j].toString());
364     }
365
366     // TO
367
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
368         for (int j = 0; j < a.length; j++)
369         pr("TO: " + a[j].toString());
370     }
371
372     // SUBJECT
373
pr("SUBJECT: " + m.getSubject());
374
375     // DATE
376
Date d = m.getSentDate();
377     pr("SendDate: " +
378         (d != null ? d.toString() : "UNKNOWN"));
379
380     // FLAGS
381
Flags flags = m.getFlags();
382     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
383     Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
384

385     boolean first = true;
386     for (int i = 0; i < sf.length; i++) {
387         String JavaDoc s;
388         Flags.Flag f = sf[i];
389         if (f == Flags.Flag.ANSWERED)
390         s = "\\Answered";
391         else if (f == Flags.Flag.DELETED)
392         s = "\\Deleted";
393         else if (f == Flags.Flag.DRAFT)
394         s = "\\Draft";
395         else if (f == Flags.Flag.FLAGGED)
396         s = "\\Flagged";
397         else if (f == Flags.Flag.RECENT)
398         s = "\\Recent";
399         else if (f == Flags.Flag.SEEN)
400         s = "\\Seen";
401         else
402         continue; // skip it
403
if (first)
404         first = false;
405         else
406         sb.append(' ');
407         sb.append(s);
408     }
409
410     String JavaDoc[] uf = flags.getUserFlags(); // get the user flag strings
411
for (int i = 0; i < uf.length; i++) {
412         if (first)
413         first = false;
414         else
415         sb.append(' ');
416         sb.append(uf[i]);
417     }
418     pr("FLAGS: " + sb.toString());
419
420     // X-MAILER
421
String JavaDoc[] hdrs = m.getHeader("X-Mailer");
422     if (hdrs != null)
423         pr("X-Mailer: " + hdrs[0]);
424     else
425         pr("X-Mailer NOT available");
426     }
427
428     static String JavaDoc indentStr = " ";
429     static int level = 0;
430
431     /**
432      * Print a, possibly indented, string.
433      */

434     public static void pr(String JavaDoc s) {
435     if (showStructure)
436         System.out.print(indentStr.substring(0, level * 2));
437     System.out.println(s);
438     }
439 }
440
Popular Tags