1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package examples.mail;
19
20 import java.io.IOException;
21
22 import org.apache.commons.net.PrintCommandListener;
23 import org.apache.commons.net.imap.IMAPClient;
24 import org.apache.commons.net.imap.IMAPSClient;
25
26
27
28
29
30
31
32
33
34 public final class IMAPMail
35 {
36
37 public static void main(String[] args)
38 {
39 if (args.length < 3)
40 {
41 System.err.println(
42 "Usage: IMAPMail <imap server hostname> <username> <password> [TLS]");
43 System.exit(1);
44 }
45
46 String server = args[0];
47 String username = args[1];
48 String password = args[2];
49
50 String proto = (args.length > 3) ? args[3] : null;
51
52 IMAPClient imap;
53
54 if (proto != null) {
55 System.out.println("Using secure protocol: " + proto);
56 imap = new IMAPSClient(proto, true);
57
58
59
60
61 } else {
62 imap = new IMAPClient();
63 }
64 System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());
65
66
67 imap.setDefaultTimeout(60000);
68
69
70 imap.addProtocolCommandListener(new PrintCommandListener(System.out, true));
71
72 try
73 {
74 imap.connect(server);
75 }
76 catch (IOException e)
77 {
78 throw new RuntimeException("Could not connect to server.", e);
79 }
80
81 try
82 {
83 if (!imap.login(username, password))
84 {
85 System.err.println("Could not login to server. Check password.");
86 imap.disconnect();
87 System.exit(3);
88 }
89
90 imap.setSoTimeout(6000);
91
92 imap.capability();
93
94 imap.select("inbox");
95
96 imap.examine("inbox");
97
98 imap.status("inbox", new String[]{"MESSAGES"});
99
100 imap.logout();
101 imap.disconnect();
102 }
103 catch (IOException e)
104 {
105 System.out.println(imap.getReplyString());
106 e.printStackTrace();
107 System.exit(10);
108 return;
109 }
110 }
111 }
112
113