List of usage examples for org.apache.commons.net.imap IMAPClient disconnect
@Override public void disconnect() throws IOException
DISCONNECTED_STATE . From source file:examples.mail.IMAPMail.java
public static void main(String[] args) { if (args.length < 3) { System.err.println("Usage: IMAPMail <imap server hostname> <username> <password> [TLS]"); System.exit(1);// w w w. ja v a 2 s .c o m } String server = args[0]; String username = args[1]; String password = args[2]; String proto = (args.length > 3) ? args[3] : null; IMAPClient imap; if (proto != null) { System.out.println("Using secure protocol: " + proto); imap = new IMAPSClient(proto, true); // implicit // enable the next line to only check if the server certificate has expired (does not check chain): // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); // OR enable the next line if the server uses a self-signed certificate (no checks) // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else { imap = new IMAPClient(); } System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort()); // We want to timeout if a response takes longer than 60 seconds imap.setDefaultTimeout(60000); // suppress login details imap.addProtocolCommandListener(new PrintCommandListener(System.out, true)); try { imap.connect(server); } catch (IOException e) { throw new RuntimeException("Could not connect to server.", e); } try { if (!imap.login(username, password)) { System.err.println("Could not login to server. Check password."); imap.disconnect(); System.exit(3); } imap.setSoTimeout(6000); imap.capability(); imap.select("inbox"); imap.examine("inbox"); imap.status("inbox", new String[] { "MESSAGES" }); imap.logout(); imap.disconnect(); } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } }
From source file:examples.mail.IMAPImportMbox.java
public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println(//from ww w . j av a 2 s.c om "Usage: IMAPImportMbox imap[s]://user:password@host[:port]/folder/path <mboxfile> [selectors]"); System.err.println("\tWhere: a selector is a list of numbers/number ranges - 1,2,3-10" + " - or a list of strings to match in the initial From line"); System.exit(1); } final URI uri = URI.create(args[0]); final String file = args[1]; final File mbox = new File(file); if (!mbox.isFile() || !mbox.canRead()) { throw new IOException("Cannot read mailbox file: " + mbox); } String path = uri.getPath(); if (path == null || path.length() < 1) { throw new IllegalArgumentException("Invalid folderPath: '" + path + "'"); } String folder = path.substring(1); // skip the leading / List<String> contains = new ArrayList<String>(); // list of strings to find BitSet msgNums = new BitSet(); // list of message numbers for (int i = 2; i < args.length; i++) { String arg = args[i]; if (arg.matches("\\d+(-\\d+)?(,\\d+(-\\d+)?)*")) { // number,m-n for (String entry : arg.split(",")) { String[] parts = entry.split("-"); if (parts.length == 2) { // m-n int low = Integer.parseInt(parts[0]); int high = Integer.parseInt(parts[1]); for (int j = low; j <= high; j++) { msgNums.set(j); } } else { msgNums.set(Integer.parseInt(entry)); } } } else { contains.add(arg); // not a number/number range } } // System.out.println(msgNums.toString()); // System.out.println(java.util.Arrays.toString(contains.toArray())); // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null); int total = 0; int loaded = 0; try { imap.setSoTimeout(6000); final BufferedReader br = new BufferedReader(new FileReader(file)); // TODO charset? String line; StringBuilder sb = new StringBuilder(); boolean wanted = false; // Skip any leading rubbish while ((line = br.readLine()) != null) { if (line.startsWith("From ")) { // start of message; i.e. end of previous (if any) if (process(sb, imap, folder, total)) { // process previous message (if any) loaded++; } sb.setLength(0); total++; wanted = wanted(total, line, msgNums, contains); } else if (startsWith(line, PATFROM)) { // Unescape ">+From " in body text line = line.substring(1); } // TODO process first Received: line to determine arrival date? if (wanted) { sb.append(line); sb.append(CRLF); } } br.close(); if (wanted && process(sb, imap, folder, total)) { // last message (if any) loaded++; } } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } finally { imap.logout(); imap.disconnect(); } System.out.println("Processed " + total + " messages, loaded " + loaded); }
From source file:jk.kamoru.test.IMAPMail.java
public static void main(String[] args) { /* if (args.length < 3) {/*from ww w. j a va 2 s. c o m*/ System.err.println( "Usage: IMAPMail <imap server hostname> <username> <password> [TLS]"); System.exit(1); } */ String server = "imap.handysoft.co.kr"; String username = "namjk24@handysoft.co.kr"; String password = "22222"; String proto = (args.length > 3) ? args[3] : null; IMAPClient imap; if (proto != null) { System.out.println("Using secure protocol: " + proto); imap = new IMAPSClient(proto, true); // implicit // enable the next line to only check if the server certificate has expired (does not check chain): // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); // OR enable the next line if the server uses a self-signed certificate (no checks) // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else { imap = new IMAPClient(); } System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort()); // We want to timeout if a response takes longer than 60 seconds imap.setDefaultTimeout(60000); File imap_log_file = new File("IMAMP-UNSEEN"); try { System.out.println(imap_log_file.getAbsolutePath()); PrintStream ps = new PrintStream(imap_log_file); // suppress login details imap.addProtocolCommandListener(new PrintCommandListener(ps, true)); } catch (FileNotFoundException e1) { imap.addProtocolCommandListener(new PrintCommandListener(System.out, true)); } try { imap.connect(server); } catch (IOException e) { throw new RuntimeException("Could not connect to server.", e); } try { if (!imap.login(username, password)) { System.err.println("Could not login to server. Check password."); imap.disconnect(); System.exit(3); } imap.setSoTimeout(6000); // imap.capability(); // imap.select("inbox"); // imap.examine("inbox"); imap.status("inbox", new String[] { "UNSEEN" }); // imap.logout(); imap.disconnect(); List<String> imap_log = FileUtils.readLines(imap_log_file); for (int i = 0; i < imap_log.size(); i++) { System.out.println(i + ":" + imap_log.get(i)); } String unseenText = imap_log.get(4); unseenText = unseenText.substring(unseenText.indexOf('(') + 1, unseenText.indexOf(')')); int unseenCount = Integer.parseInt(unseenText.split(" ")[1]); System.out.println(unseenCount); //imap_log.indexOf("UNSEEN ") } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } }
From source file:examples.mail.IMAPExportMbox.java
public static void main(String[] args) throws IOException { int connect_timeout = CONNECT_TIMEOUT; int read_timeout = READ_TIMEOUT; int argIdx = 0; String eol = EOL_DEFAULT;/* ww w .java 2s .c om*/ boolean printHash = false; boolean printMarker = false; int retryWaitSecs = 0; for (argIdx = 0; argIdx < args.length; argIdx++) { if (args[argIdx].equals("-c")) { connect_timeout = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-r")) { read_timeout = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-R")) { retryWaitSecs = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-LF")) { eol = LF; } else if (args[argIdx].equals("-CRLF")) { eol = CRLF; } else if (args[argIdx].equals("-.")) { printHash = true; } else if (args[argIdx].equals("-X")) { printMarker = true; } else { break; } } final int argCount = args.length - argIdx; if (argCount < 2) { System.err.println("Usage: IMAPExportMbox [-LF|-CRLF] [-c n] [-r n] [-R n] [-.] [-X]" + " imap[s]://user:password@host[:port]/folder/path [+|-]<mboxfile> [sequence-set] [itemnames]"); System.err.println( "\t-LF | -CRLF set end-of-line to LF or CRLF (default is the line.separator system property)"); System.err.println("\t-c connect timeout in seconds (default 10)"); System.err.println("\t-r read timeout in seconds (default 10)"); System.err.println("\t-R temporary failure retry wait in seconds (default 0; i.e. disabled)"); System.err.println("\t-. print a . for each complete message received"); System.err.println("\t-X print the X-IMAP line for each complete message received"); System.err.println( "\tthe mboxfile is where the messages are stored; use '-' to write to standard output."); System.err.println( "\tPrefix filename with '+' to append to the file. Prefix with '-' to allow overwrite."); System.err.println( "\ta sequence-set is a list of numbers/number ranges e.g. 1,2,3-10,20:* - default 1:*"); System.err .println("\titemnames are the message data item name(s) e.g. BODY.PEEK[HEADER.FIELDS (SUBJECT)]" + " or a macro e.g. ALL - default (INTERNALDATE BODY.PEEK[])"); System.exit(1); } final URI uri = URI.create(args[argIdx++]); final String file = args[argIdx++]; String sequenceSet = argCount > 2 ? args[argIdx++] : "1:*"; final String itemNames; // Handle 0, 1 or multiple item names if (argCount > 3) { if (argCount > 4) { StringBuilder sb = new StringBuilder(); sb.append("("); for (int i = 4; i <= argCount; i++) { if (i > 4) { sb.append(" "); } sb.append(args[argIdx++]); } sb.append(")"); itemNames = sb.toString(); } else { itemNames = args[argIdx++]; } } else { itemNames = "(INTERNALDATE BODY.PEEK[])"; } final boolean checkSequence = sequenceSet.matches("\\d+:(\\d+|\\*)"); // are we expecting a sequence? final MboxListener chunkListener; if (file.equals("-")) { chunkListener = null; } else if (file.startsWith("+")) { final File mbox = new File(file.substring(1)); System.out.println("Appending to file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, true)), eol, printHash, printMarker, checkSequence); } else if (file.startsWith("-")) { final File mbox = new File(file.substring(1)); System.out.println("Writing to file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, false)), eol, printHash, printMarker, checkSequence); } else { final File mbox = new File(file); if (mbox.exists()) { throw new IOException("mailbox file: " + mbox + " already exists!"); } System.out.println("Creating file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox)), eol, printHash, printMarker, checkSequence); } String path = uri.getPath(); if (path == null || path.length() < 1) { throw new IllegalArgumentException("Invalid folderPath: '" + path + "'"); } String folder = path.substring(1); // skip the leading / // suppress login details final PrintCommandListener listener = new PrintCommandListener(System.out, true) { @Override public void protocolReplyReceived(ProtocolCommandEvent event) { if (event.getReplyCode() != IMAPReply.PARTIAL) { // This is dealt with by the chunk listener super.protocolReplyReceived(event); } } }; // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, connect_timeout * 1000, listener); String maxIndexInFolder = null; try { imap.setSoTimeout(read_timeout * 1000); if (!imap.select(folder)) { throw new IOException("Could not select folder: " + folder); } for (String line : imap.getReplyStrings()) { maxIndexInFolder = matches(line, PATEXISTS, 1); if (maxIndexInFolder != null) { break; } } if (chunkListener != null) { imap.setChunkListener(chunkListener); } // else the command listener displays the full output without processing while (true) { boolean ok = imap.fetch(sequenceSet, itemNames); // If the fetch failed, can we retry? if (!ok && retryWaitSecs > 0 && chunkListener != null && checkSequence) { final String replyString = imap.getReplyString(); //includes EOL if (startsWith(replyString, PATTEMPFAIL)) { System.err.println("Temporary error detected, will retry in " + retryWaitSecs + "seconds"); sequenceSet = (chunkListener.lastSeq + 1) + ":*"; try { Thread.sleep(retryWaitSecs * 1000); } catch (InterruptedException e) { // ignored } } else { throw new IOException( "FETCH " + sequenceSet + " " + itemNames + " failed with " + replyString); } } else { break; } } } catch (IOException ioe) { String count = chunkListener == null ? "?" : Integer.toString(chunkListener.total); System.err.println("FETCH " + sequenceSet + " " + itemNames + " failed after processing " + count + " complete messages "); if (chunkListener != null) { System.err.println("Last complete response seen: " + chunkListener.lastFetched); } throw ioe; } finally { if (printHash) { System.err.println(); } if (chunkListener != null) { chunkListener.close(); final Iterator<String> missingIds = chunkListener.missingIds.iterator(); if (missingIds.hasNext()) { StringBuilder sb = new StringBuilder(); for (;;) { sb.append(missingIds.next()); if (!missingIds.hasNext()) { break; } sb.append(","); } System.err.println("*** Missing ids: " + sb.toString()); } } imap.logout(); imap.disconnect(); } if (chunkListener != null) { System.out.println("Processed " + chunkListener.total + " messages."); } if (maxIndexInFolder != null) { System.out.println("Folder contained " + maxIndexInFolder + " messages."); } }
From source file:Main.java
/** * Parse the URI and use the details to connect to the IMAP(S) server and login. * * @param uri the URI to use, e.g. imaps://user:pass@imap.mail.yahoo.com/folder * or imaps://user:pass@imap.googlemail.com/folder * @param defaultTimeout initial timeout (in milliseconds) * @param listener for tracing protocol IO (may be null) * @return the IMAP client - connected and logged in * @throws IOException if any problems occur *///from ww w . ja v a 2 s . c om static IMAPClient imapLogin(URI uri, int defaultTimeout, ProtocolCommandListener listener) throws IOException { final String userInfo = uri.getUserInfo(); if (userInfo == null) { throw new IllegalArgumentException("Missing userInfo details"); } String[] userpass = userInfo.split(":"); if (userpass.length != 2) { throw new IllegalArgumentException("Invalid userInfo details: '" + userpass + "'"); } String username = userpass[0]; String password = userpass[1]; // TODO enable reading this secretly final IMAPClient imap; final String scheme = uri.getScheme(); if ("imaps".equalsIgnoreCase(scheme)) { System.out.println("Using secure protocol"); imap = new IMAPSClient(true); // implicit } else if ("imap".equalsIgnoreCase(scheme)) { imap = new IMAPClient(); } else { throw new IllegalArgumentException("Invalid protocol: " + scheme); } final int port = uri.getPort(); if (port != -1) { imap.setDefaultPort(port); } imap.setDefaultTimeout(defaultTimeout); if (listener != null) { imap.addProtocolCommandListener(listener); } final String server = uri.getHost(); System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort()); try { imap.connect(server); System.out.println("Successfully connected"); } catch (IOException e) { throw new RuntimeException("Could not connect to server.", e); } if (!imap.login(username, password)) { imap.disconnect(); throw new RuntimeException("Could not login to server. Check login details."); } return imap; }
From source file:examples.mail.IMAPUtils.java
/** * Parse the URI and use the details to connect to the IMAP(S) server and login. * * @param uri the URI to use, e.g. imaps://user:pass@imap.mail.yahoo.com/folder * or imaps://user:pass@imap.googlemail.com/folder * @param defaultTimeout initial timeout (in milliseconds) * @param listener for tracing protocol IO (may be null) * @return the IMAP client - connected and logged in * @throws IOException if any problems occur */// ww w. j a va 2s . co m static IMAPClient imapLogin(URI uri, int defaultTimeout, ProtocolCommandListener listener) throws IOException { final String userInfo = uri.getUserInfo(); if (userInfo == null) { throw new IllegalArgumentException("Missing userInfo details"); } String[] userpass = userInfo.split(":"); if (userpass.length != 2) { throw new IllegalArgumentException("Invalid userInfo details: '" + userInfo + "'"); } String username = userpass[0]; String password = userpass[1]; /* * If the initial password is: * '*' - replace it with a line read from the system console * '-' - replace it with next line from STDIN * 'ABCD' - if the input is all upper case, use the field as an environment variable name * * Note: there are no guarantees that the password cannot be snooped. * * Even using the console may be subject to memory snooping, * however it should be safer than the other methods. * * STDIN may require creating a temporary file which could be read by others * Environment variables may be visible by using PS */ if ("-".equals(password)) { // stdin BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); password = in.readLine(); } else if ("*".equals(password)) { // console Console con = System.console(); // Java 1.6 if (con != null) { char[] pwd = con.readPassword("Password for " + username + ": "); password = new String(pwd); } else { throw new IOException("Cannot access Console"); } } else if (password.equals(password.toUpperCase(Locale.ROOT))) { // environment variable name final String tmp = System.getenv(password); if (tmp != null) { // don't overwrite if variable does not exist (just in case password is all uppers) password = tmp; } } final IMAPClient imap; final String scheme = uri.getScheme(); if ("imaps".equalsIgnoreCase(scheme)) { System.out.println("Using secure protocol"); imap = new IMAPSClient(true); // implicit } else if ("imap".equalsIgnoreCase(scheme)) { imap = new IMAPClient(); } else { throw new IllegalArgumentException("Invalid protocol: " + scheme); } final int port = uri.getPort(); if (port != -1) { imap.setDefaultPort(port); } imap.setDefaultTimeout(defaultTimeout); if (listener != null) { imap.addProtocolCommandListener(listener); } final String server = uri.getHost(); System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort()); try { imap.connect(server); System.out.println("Successfully connected"); } catch (IOException e) { throw new RuntimeException("Could not connect to server.", e); } if (!imap.login(username, password)) { imap.disconnect(); throw new RuntimeException("Could not login to server. Check login details."); } return imap; }
From source file:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java
private SampleResult sampleDisconnect(SampleResult sr) { SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient()); IMAPClient client = null; if (soclient instanceof IMAPClient) client = (IMAPClient) soclient;//from ww w.j a v a2 s.c o m String request = "DISCONNECT \n"; request += "Client : " + getClient() + "\n"; sr.setRequestHeaders(request); if (client == null) { clientNotFound(sr); return sr; } else { synchronized (client) { sr.sampleStart(); try { client.disconnect(); SessionStorage.getInstance().removeClient(getSOClient()); sr.setSuccessful(true); sr.setResponseCodeOK(); sr.setResponseData(client.getReplyString().getBytes()); } catch (IOException e) { sr.setSuccessful(false); sr.setResponseData(e.toString().getBytes()); sr.setResponseCode(e.getClass().getName()); log.error("client `" + getClient() + "` ", e); removeClient(); } finally { sr.sampleEnd(); } } } return sr; }
From source file:com.clustercontrol.port.protocol.ReachAddressIMAP.java
/** * IMAP????????/*from w w w. j av a2 s . c o m*/ * * @param addressText * @return IMAP */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // boolean retry = true; // ????(true:??false:???) StringBuffer bufferOrg = new StringBuffer(); // String result = ""; InetAddress address = InetAddress.getByName(addressText); bufferOrg.append("Monitoring the IMAP Service of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); IMAPClient client = new IMAPClient(); for (int i = 0; i < m_sentCount && retry; i++) { try { bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); client.setDefaultTimeout(m_timeout); start = HinemosTime.currentTimeMillis(); client.connect(address, m_portNo); end = HinemosTime.currentTimeMillis(); m_response = end - start; result = client.getReplyString(); if (m_response > 0) { if (m_response < m_timeout) { result = result + ("\n" + "Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = result + ("\n" + "Response Time = " + m_response + "ms"); } } else { result = result + ("\n" + "Response Time < 1ms"); } retry = false; isReachable = true; } catch (SocketException e) { result = (e.getMessage() + "[SocketException]"); retry = true; isReachable = false; } catch (IOException e) { result = (e.getMessage() + "[IOException]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e); } } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(IMAP/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage()); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:com.google.gerrit.server.mail.receive.ImapMailReceiver.java
/** * handleEmails will open a connection to the mail server, remove emails where deletion is * pending, read new email and close the connection. * * @param async Determines if processing messages should happen asynchronous. *//*from ww w.ja v a2 s . com*/ @Override public synchronized void handleEmails(boolean async) { IMAPClient imap; if (mailSettings.encryption != Encryption.NONE) { imap = new IMAPSClient(mailSettings.encryption.name(), false); } else { imap = new IMAPClient(); } if (mailSettings.port > 0) { imap.setDefaultPort(mailSettings.port); } // Set a 30s timeout for each operation imap.setDefaultTimeout(30 * 1000); try { imap.connect(mailSettings.host); try { if (!imap.login(mailSettings.username, mailSettings.password)) { log.error("Could not login to IMAP server"); return; } try { if (!imap.select(INBOX_FOLDER)) { log.error("Could not select IMAP folder " + INBOX_FOLDER); return; } // Fetch just the internal dates first to know how many messages we // should fetch. if (!imap.fetch("1:*", "(INTERNALDATE)")) { log.error("IMAP fetch failed. Will retry in next fetch cycle."); return; } // Format of reply is one line per email and one line to indicate // that the fetch was successful. // Example: // * 1 FETCH (INTERNALDATE "Mon, 24 Oct 2016 16:53:22 +0200 (CEST)") // * 2 FETCH (INTERNALDATE "Mon, 24 Oct 2016 16:53:22 +0200 (CEST)") // AAAC OK FETCH completed. int numMessages = imap.getReplyStrings().length - 1; log.info("Fetched " + numMessages + " messages via IMAP"); if (numMessages == 0) { return; } // Fetch the full version of all emails List<MailMessage> mailMessages = new ArrayList<>(numMessages); for (int i = 1; i <= numMessages; i++) { if (imap.fetch(i + ":" + i, "(BODY.PEEK[])")) { // Obtain full reply String[] rawMessage = imap.getReplyStrings(); if (rawMessage.length < 2) { continue; } // First and last line are IMAP status codes. We have already // checked, that the fetch returned true (OK), so we safely ignore // those two lines. StringBuilder b = new StringBuilder(2 * (rawMessage.length - 2)); for (int j = 1; j < rawMessage.length - 1; j++) { if (j > 1) { b.append("\n"); } b.append(rawMessage[j]); } try { MailMessage mailMessage = RawMailParser.parse(b.toString()); if (pendingDeletion.contains(mailMessage.id())) { // Mark message as deleted if (imap.store(i + ":" + i, "+FLAGS", "(\\Deleted)")) { pendingDeletion.remove(mailMessage.id()); } else { log.error("Could not mark mail message as deleted: " + mailMessage.id()); } } else { mailMessages.add(mailMessage); } } catch (MailParsingException e) { log.error("Exception while parsing email after IMAP fetch", e); } } else { log.error("IMAP fetch failed. Will retry in next fetch cycle."); } } // Permanently delete emails marked for deletion if (!imap.expunge()) { log.error("Could not expunge IMAP emails"); } dispatchMailProcessor(mailMessages, async); } finally { imap.logout(); } } finally { imap.disconnect(); } } catch (IOException e) { log.error("Error while talking to IMAP server", e); return; } }
From source file:org.apache.common.net.examples.mail.IMAPMail.java
public static final void main(String[] args) { if (args.length < 3) { System.err.println("Usage: IMAPMail <imap server hostname> <username> <password> [TLS]"); System.exit(1);/* ww w . j a v a2 s.c o m*/ } String server = args[0]; String username = args[1]; String password = args[2]; String proto = (args.length > 3) ? args[3] : null; IMAPClient imap; if (proto != null) { System.out.println("Using secure protocol: " + proto); imap = new IMAPSClient(proto, true); // implicit // enable the next line to only check if the server certificate has expired (does not check chain): // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); // OR enable the next line if the server uses a self-signed certificate (no checks) // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else { imap = new IMAPClient(); } System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort()); // We want to timeout if a response takes longer than 60 seconds imap.setDefaultTimeout(60000); // suppress login details imap.addProtocolCommandListener(new PrintCommandListener(System.out, true)); try { imap.connect(server); } catch (IOException e) { throw new RuntimeException("Could not connect to server.", e); } try { if (!imap.login(username, password)) { System.err.println("Could not login to server. Check password."); imap.disconnect(); System.exit(3); } imap.setSoTimeout(6000); imap.capability(); imap.select("inbox"); imap.examine("inbox"); imap.status("inbox", new String[] { "MESSAGES" }); imap.logout(); imap.disconnect(); } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } }