Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

412
LINES

< > BotCompany Repo | #1003228 // msgshow (JavaMail example)

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

Uses 590K of libraries. Click here for Pure Java version (436L/4K/11K).

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

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1003228
Snippet name: msgshow (JavaMail example)
Eternal ID of this version: #1003228/1
Text MD5: ef569ed35fbf1986bd96729df0e714fa
Transpilation MD5: a7329e71df9444c9429be723f8b25882
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-06-03 04:28:15
Source code size: 11384 bytes / 412 lines
Pitched / IR pitched: No / No
Views / Downloads: 613 / 608
Referenced in: [show references]