List of usage examples for org.apache.commons.net.imap IMAPClient connect
public void connect(InetAddress host) throws SocketException, IOException
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);//from w ww . j av 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:jk.kamoru.test.IMAPMail.java
public static void main(String[] args) { /* if (args.length < 3) {//from w w w . ja v a 2 s . com 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: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 */// ww w . j ava 2 s . c o 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: '" + 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 .ja v a 2 s . c o 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: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. *//*w w w.j a v a 2 s . c o m*/ @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);/*w ww. j a v a 2 s.co 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:org.apache.commons.net.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 *//*from w w w . j a va 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: '" + userInfo + "'"); } String username = userpass[0]; String password = userpass[1]; // prompt for the password if necessary password = Utils.getPassword(username, password); 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; }