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

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

Introduction

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

Prototype

public IMAPSClient(boolean implicit, SSLContext ctx) 

Source Link

Document

Constructor for IMAPSClient.

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);/* w w 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;
    }
}

From source file:jk.kamoru.test.IMAPMail.java

public static void main(String[] args) {
    /*        if (args.length < 3)
            {//from   w  w  w  . j  a  v a  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: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  w ww .j a  va2 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);//  www  .  j a va 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;
    }
}