Debian Codegraph @

demo/src/main/java/msgshow.java

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