Example usage for org.apache.commons.net.imap IMAPClient IMAPClient

List of usage examples for org.apache.commons.net.imap IMAPClient IMAPClient

Introduction

In this page you can find the example usage for org.apache.commons.net.imap IMAPClient IMAPClient.

Prototype

IMAPClient

Source Link

Usage

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 a 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:jk.kamoru.test.IMAPMail.java

public static void main(String[] args) {
    /*        if (args.length < 3)
            {//from  w w w .  j  ava 2s.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: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
 *//* www . j a  va2s  .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: '" + 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: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.
 *//*  ww  w . ja v a  2  s  . c  om*/
@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:com.clustercontrol.port.protocol.ReachAddressIMAP.java

/**
 * IMAP????????//from  w  w w  .j a 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: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
 *///w ww. j a  v a2 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:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java

private SampleResult sampleConnect(SampleResult sr) {
    IMAPClient client;//from   w  w w .j av a  2 s.co m
    if (getUseSSL()) {
        client = new IMAPSClient(true);
    } else {
        client = new IMAPClient();
    }
    try {
        String request = "CONNECT \n";
        request += "Host : " + getHostname() + ":" + getPort() + "\n";
        request += "Default Timeout : " + getDefaultTimeout() + "\n";
        request += "Connect Timeout : " + getConnectionTimeout() + "\n";
        request += "So Timeout : " + getSoTimeout() + "\n";
        request += "Client : " + getClient() + "\n";

        sr.setRequestHeaders(request);
        sr.sampleStart();
        client.setDefaultTimeout(getDefaultTimeout());
        client.setConnectTimeout(getConnectionTimeout());
        if (getLocalAddr().isEmpty())
            client.connect(getHostname(), getPort());
        else
            client.connect(getHostname(), getPort(), InetAddress.getByName(getLocalAddr()), 0);
        if (client.isConnected()) {
            log.info("imap client " + getClient() + " connected from " + client.getLocalAddress() + ":"
                    + client.getLocalPort());
            SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN;
            if (getUseSSL())
                protoType = SessionStorage.proto_type.SSL;
            SessionStorage.getInstance().putClient(getSOClient(), client, protoType);
            client.setSoTimeout(getSoTimeout());
            sr.setSuccessful(true);
            sr.setResponseCodeOK();
            sr.setResponseData(client.getReplyString().getBytes());
        } else {
            client.close();
            sr.setSuccessful(false);
            sr.setResponseCode("java.net.ConnectException");
            sr.setResponseMessage("Not connected");
        }
    } catch (SocketException se) {
        sr.setResponseMessage(se.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(se.getClass().getName());
        log.error("client `" + getClient() + "` ", se);
        removeClient();
    } catch (IOException ioe) {
        sr.setResponseMessage(ioe.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(ioe.getClass().getName());
        log.error("client `" + getClient() + "` ", ioe);
        removeClient();
    } finally {
        sr.sampleEnd();
    }
    return sr;
}

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);//from   w w w  .j  a  v  a 2s  .  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
 *///w  ww.j ava2 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];
    // 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;
}

From source file:org.apache.james.ESReporterTest.java

@Test
public void timeMetricsShouldBeReportedWhenImapCommandsReceived() throws Exception {
    IMAPClient client = new IMAPClient();
    client.connect(InetAddress.getLocalHost(), IMAP_PORT);
    client.login(USERNAME, PASSWORD);/*from w  w w  .j  ava 2s .com*/

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            try {
                client.list("", "*");
            } catch (Exception e) {
                LOGGER.error("Error while sending LIST command", e);
            }
        }
    };
    timer.schedule(timerTask, DELAY_IN_MS, PERIOD_IN_MS);

    await().atMost(Duration.TEN_MINUTES).until(() -> checkMetricRecordedInElasticSearch());
}