1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.net.examples.mail;
19
20 import java.io.IOException;
21 import java.net.URI;
22
23 import org.apache.commons.net.ProtocolCommandListener;
24 import org.apache.commons.net.imap.IMAPClient;
25 import org.apache.commons.net.imap.IMAPSClient;
26
27
28
29
30 class IMAPUtils {
31
32
33
34
35
36
37
38
39
40
41 static IMAPClient imapLogin(final URI uri, final int defaultTimeout, final ProtocolCommandListener listener) throws IOException {
42 final String userInfo = uri.getUserInfo();
43 if (userInfo == null) {
44 throw new IllegalArgumentException("Missing userInfo details");
45 }
46
47 final String[] userPassword = userInfo.split(":");
48 if (userPassword.length != 2) {
49 throw new IllegalArgumentException("Invalid userInfo details: '" + userInfo + "'");
50 }
51
52 final String user = userPassword[0];
53 String password = userPassword[1];
54
55 password = Utils.getPassword(user, password);
56
57 final IMAPClient imap;
58
59 final String scheme = uri.getScheme();
60 if ("imaps".equalsIgnoreCase(scheme)) {
61 System.out.println("Using secure protocol");
62 imap = new IMAPSClient(true);
63 } else if ("imap".equalsIgnoreCase(scheme)) {
64 imap = new IMAPClient();
65 } else {
66 throw new IllegalArgumentException("Invalid protocol: " + scheme);
67 }
68 final int port = uri.getPort();
69 if (port != -1) {
70 imap.setDefaultPort(port);
71 }
72
73 imap.setDefaultTimeout(defaultTimeout);
74
75 if (listener != null) {
76 imap.addProtocolCommandListener(listener);
77 }
78
79 final String server = uri.getHost();
80 System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());
81
82 try {
83 imap.connect(server);
84 System.out.println("Successfully connected");
85 } catch (final IOException e) {
86 throw new IOException("Could not connect to server.", e);
87 }
88
89 if (!imap.login(user, password)) {
90 imap.disconnect();
91 throw new IOException("Could not login to server. Check login details.");
92 }
93
94 return imap;
95 }
96 }