List of usage examples for org.apache.commons.net.imap IMAPClient getReplyString
public String getReplyString()
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;//from ww w .j a v a 2 s.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:examples.mail.IMAPImportMbox.java
public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println(/*from w w w . j a v a 2 s . com*/ "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: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);/* ww w . ja v a 2 s .com*/ } 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:jk.kamoru.test.IMAPMail.java
public static void main(String[] args) { /* if (args.length < 3) {/*from ww w .j a va 2 s . co 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.IMAPImportMbox.java
private static boolean process(final StringBuilder sb, final IMAPClient imap, final String folder, final int msgNum) throws IOException { final int length = sb.length(); boolean haveMessage = length > 2; if (haveMessage) { System.out.println("MsgNum: " + msgNum + " Length " + length); sb.setLength(length - 2); // drop trailing CRLF String msg = sb.toString(); if (!imap.append(folder, null, null, msg)) { throw new IOException("Failed to import message: " + msgNum + " " + imap.getReplyString()); }// w ww . j a v a 2 s. c o m } return haveMessage; }
From source file:com.clustercontrol.port.protocol.ReachAddressIMAP.java
/** * IMAP????????// ww w . ja v a 2 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: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 w ww . jav 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:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java
private SampleResult sampleNoop(SampleResult sr) { SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient()); IMAPClient client = null; if (soclient instanceof IMAPClient) client = (IMAPClient) soclient;// ww w . j a v a 2s . com boolean success = false; String request = "NOOP\n"; request += "Client : " + getClient() + "\n"; sr.setRequestHeaders(request); if (client == null) { clientNotFound(sr); return sr; } else { synchronized (client) { sr.sampleStart(); try { success = client.noop(); if (getCheckSuccessful()) { sr.setSuccessful(success); if (success) sr.setResponseCodeOK(); else sr.setResponseCode(RC_ERROR); } else { 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() + "` io exception", e); removeClient(); } sr.sampleEnd(); } } return sr; }
From source file:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java
private SampleResult sampleLogout(SampleResult sr) { SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient()); IMAPClient client = null; if (soclient instanceof IMAPClient) client = (IMAPClient) soclient;//from ww w. j a va 2 s . com boolean success = false; String request = "LOGOUT\n"; request += "Client : " + getClient() + "\n"; request += "Client Name : " + getClientName() + "\n"; sr.setRequestHeaders(request); if (client == null) { clientNotFound(sr); return sr; } else { synchronized (client) { sr.sampleStart(); try { success = client.logout(); sr.setSuccessful(success); if (getCheckSuccessful()) { sr.setSuccessful(success); if (success) sr.setResponseCodeOK(); else sr.setResponseCode(RC_ERROR); } else 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(); } sr.sampleEnd(); } } return sr; }
From source file:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java
private SampleResult sampleCapability(SampleResult sr) { SocketClient soclient = SessionStorage.getInstance().getClient(getSOClient()); IMAPClient client = null; if (soclient instanceof IMAPClient) client = (IMAPClient) soclient;/*from w w w .ja va 2 s . co m*/ boolean success = false; String request = "CAPABILITY \n"; request += "Client : " + getClient() + "\n"; request += "Client Name : " + getClientName() + "\n"; sr.setRequestHeaders(request); if (client == null) { clientNotFound(sr); return sr; } else { synchronized (client) { sr.sampleStart(); try { success = client.capability(); sr.setSuccessful(success); if (getCheckSuccessful()) { sr.setSuccessful(success); if (success) sr.setResponseCodeOK(); else sr.setResponseCode(RC_ERROR); } else 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(); } sr.sampleEnd(); } } return sr; }