Example usage for org.apache.commons.net.pop3 POP3Client POP3Client

List of usage examples for org.apache.commons.net.pop3 POP3Client POP3Client

Introduction

In this page you can find the example usage for org.apache.commons.net.pop3 POP3Client POP3Client.

Prototype

POP3Client

Source Link

Usage

From source file:examples.messages.java

public static final void main(String[] args) {
    int message;//  ww w  . j av  a 2 s. co m
    String server, username, password;
    POP3Client pop3;
    Reader reader;
    POP3MessageInfo[] messages;

    if (args.length < 3) {
        System.err.println("Usage: messages <pop3 server hostname> <username> <password>");
        System.exit(1);
    }

    server = args[0];
    username = args[1];
    password = args[2];

    pop3 = new POP3Client();
    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            System.exit(1);
        }

        messages = pop3.listMessages();

        if (messages == null) {
            System.err.println("Could not retrieve message list.");
            pop3.disconnect();
            System.exit(1);
        } else if (messages.length == 0) {
            System.out.println("No messages");
            pop3.logout();
            pop3.disconnect();
            System.exit(1);
        }

        for (message = 0; message < messages.length; message++) {
            reader = pop3.retrieveMessageTop(messages[message].number, 0);

            if (reader == null) {
                System.err.println("Could not retrieve message header.");
                pop3.disconnect();
                System.exit(1);
            }

            printMessageInfo(new BufferedReader(reader), messages[message].number);
        }

        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.xiangzhurui.util.email.POP3Mail.java

public static void main(String[] args) {
    if (args.length < 3) {
        System.err//from  w  w  w. ja  v  a2s  . com
                .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]");
        System.exit(1);
    }

    String server = args[0];
    String username = args[1];
    String password = args[2];

    String proto = args.length > 3 ? args[3] : null;
    boolean implicit = args.length > 4 && Boolean.parseBoolean(args[4]);

    POP3Client pop3;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        pop3 = new POP3SClient(proto, implicit);
    } else {
        pop3 = new POP3Client();
    }
    System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    // suppress login details
    pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            System.exit(1);
        }

        POP3MessageInfo[] messages = pop3.listMessages();

        if (messages == null) {
            System.err.println("Could not retrieve message list.");
            pop3.disconnect();
            return;
        } else if (messages.length == 0) {
            System.out.println("No messages");
            pop3.logout();
            pop3.disconnect();
            return;
        }

        for (POP3MessageInfo msginfo : messages) {
            BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);

            if (reader == null) {
                System.err.println("Could not retrieve message header.");
                pop3.disconnect();
                System.exit(1);
            }
            printMessageInfo(reader, msginfo.number);
        }

        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

From source file:examples.mail.POP3Mail.java

public static void main(String[] args) {
    if (args.length < 3) {
        System.err//from w  ww.j a  va2s  .c o m
                .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]");
        System.exit(1);
    }

    String server = args[0];
    String username = args[1];
    String password = args[2];

    String proto = args.length > 3 ? args[3] : null;
    boolean implicit = args.length > 4 ? Boolean.parseBoolean(args[4]) : false;

    POP3Client pop3;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        pop3 = new POP3SClient(proto, implicit);
    } else {
        pop3 = new POP3Client();
    }
    System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    // suppress login details
    pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            System.exit(1);
        }

        POP3MessageInfo[] messages = pop3.listMessages();

        if (messages == null) {
            System.err.println("Could not retrieve message list.");
            pop3.disconnect();
            return;
        } else if (messages.length == 0) {
            System.out.println("No messages");
            pop3.logout();
            pop3.disconnect();
            return;
        }

        for (POP3MessageInfo msginfo : messages) {
            BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);

            if (reader == null) {
                System.err.println("Could not retrieve message header.");
                pop3.disconnect();
                System.exit(1);
            }
            printMessageInfo(reader, msginfo.number);
        }

        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

From source file:POP3Mail.java

public static void main(String[] args) {
    try {//w w w  . j av  a2s  . c  o m
        LogManager.getLogManager().readConfiguration(new FileInputStream("logging.properties"));
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String server = null;
    String username = null;
    String password = null;
    if (new File("mail.properties").exists()) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(new File("mail.properties")));
            server = properties.getProperty("server");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            ArrayList<String> list = new ArrayList<String>(
                    Arrays.asList(new String[] { server, username, password }));
            list.addAll(Arrays.asList(args));
            args = list.toArray(new String[list.size()]);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (args.length < 3) {
        System.err
                .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]");
        System.exit(1);
    }

    server = args[0];
    username = args[1];
    password = args[2];
    String proto = null;
    int messageid = -1;
    boolean implicit = false;
    for (int i = 3; i < args.length; ++i) {
        if (args[i].equals("-m")) {
            i += 1;
            messageid = Integer.parseInt(args[i]);
        }
    }

    // String proto = args.length > 3 ? args[3] : null;
    // boolean implicit = args.length > 4 ? Boolean.parseBoolean(args[4])
    // : false;

    POP3Client pop3;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        pop3 = new POP3SClient(proto, implicit);
    } else {
        pop3 = new POP3Client();
    }
    pop3.setDefaultPort(110);
    System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);
    // suppress login details
    pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        pop3.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        if (!pop3.login(username, password)) {
            System.err.println("Could not login to server.  Check password.");
            pop3.disconnect();
            System.exit(1);
        }
        PrintWriter printWriter = new PrintWriter(new FileWriter("messages.csv"), true);
        POP3MessageInfo[] messages = null;
        POP3MessageInfo[] identifiers = null;
        if (messageid == -1) {
            messages = pop3.listMessages();
            identifiers = pop3.listUniqueIdentifiers();
        } else {
            messages = new POP3MessageInfo[] { pop3.listMessage(messageid) };
        }
        if (messages == null) {
            System.err.println("Could not retrieve message list.");
            pop3.disconnect();
            return;
        } else if (messages.length == 0) {
            System.out.println("No messages");
            pop3.logout();
            pop3.disconnect();
            return;
        }
        new File("../json").mkdirs();
        int count = 0;
        for (POP3MessageInfo msginfo : messages) {
            if (msginfo.number != identifiers[count].number) {
                throw new RuntimeException();
            }
            msginfo.identifier = identifiers[count].identifier;
            BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);
            ++count;
            if (count % 100 == 0) {
                logger.finest(String.format("%d %s", msginfo.number, msginfo.identifier));
            }
            System.out.println(String.format("%d %s", msginfo.number, msginfo.identifier));
            if (reader == null) {
                System.err.println("Could not retrieve message header.");
                pop3.disconnect();
                System.exit(1);
            }
            if (printMessageInfo(reader, msginfo.number, printWriter)) {
            }
        }
        printWriter.close();
        pop3.logout();
        pop3.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

From source file:com.adaptris.mail.ApachePOP3.java

@Override
POP3Client createClient() throws MailException {
    return new POP3Client();
}

From source file:com.discursive.jccook.net.POPExample.java

public void start() throws SocketException, IOException {
    POP3Client client = new POP3Client();
    client.connect("www.discursive.com");
    client.login("tobrien@discursive.com", "******");

    POP3MessageInfo[] messages = client.listMessages();
    for (int i = 0; i < 5; i++) {
        int messageNum = messages[i].number;
        System.out.println("Message number: " + messageNum);
        Reader reader = client.retrieveMessageTop(messageNum, 10);
        System.out.println("Message:\n" + IOUtils.toString(reader));
        IOUtils.closeQuietly(reader);/*w  w w.j a  va  2s.c  o  m*/
    }

    client.logout();
    client.disconnect();
}

From source file:com.wavechain.utilities.MailListenerUtil.java

public MailListenerUtil(String serverId, String userId, String password) {
    this.serverId = serverId;
    this.userId = userId;
    this.password = password;

    if (StringUtil.isEmpty(serverId) || StringUtil.isEmpty(userId) || StringUtil.isEmpty(password)) {
        log.fatal("Please pass a valid serverId, userId and password");
        return;/*from  ww w  .j av  a  2  s  .com*/
    }

    pop3 = new POP3Client();
    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    try {
        pop3.connect(serverId);
    } catch (IOException e) {
        log.fatal("Could not connect to server: " + serverId);
        return;
    }
}

From source file:com.google.gerrit.server.mail.receive.Pop3MailReceiver.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 2s.  c o m
@Override
public synchronized void handleEmails(boolean async) {
    POP3Client pop3;
    if (mailSettings.encryption != Encryption.NONE) {
        pop3 = new POP3SClient(mailSettings.encryption.name());
    } else {
        pop3 = new POP3Client();
    }
    if (mailSettings.port > 0) {
        pop3.setDefaultPort(mailSettings.port);
    }
    try {
        pop3.connect(mailSettings.host);
    } catch (IOException e) {
        log.error("Could not connect to POP3 email server", e);
        return;
    }
    try {
        try {
            if (!pop3.login(mailSettings.username, mailSettings.password)) {
                log.error("Could not login to POP3 email server. Check username and password");
                return;
            }
            try {
                POP3MessageInfo[] messages = pop3.listMessages();
                if (messages == null) {
                    log.error("Could not retrieve message list via POP3");
                    return;
                }
                log.info("Received " + messages.length + " messages via POP3");
                // Fetch messages
                List<MailMessage> mailMessages = new ArrayList<>();
                for (POP3MessageInfo msginfo : messages) {
                    if (msginfo == null) {
                        // Message was deleted
                        continue;
                    }
                    try (BufferedReader reader = (BufferedReader) pop3.retrieveMessage(msginfo.number)) {
                        if (reader == null) {
                            log.error("Could not retrieve POP3 message header for message {}",
                                    msginfo.identifier);
                            return;
                        }
                        int[] message = fetchMessage(reader);
                        MailMessage mailMessage = RawMailParser.parse(message);
                        // Delete messages where deletion is pending. This requires
                        // knowing the integer message ID of the email. We therefore parse
                        // the message first and extract the Message-ID specified in RFC
                        // 822 and delete the message if deletion is pending.
                        if (pendingDeletion.contains(mailMessage.id())) {
                            if (pop3.deleteMessage(msginfo.number)) {
                                pendingDeletion.remove(mailMessage.id());
                            } else {
                                log.error("Could not delete message " + msginfo.number);
                            }
                        } else {
                            // Process message further
                            mailMessages.add(mailMessage);
                        }
                    } catch (MailParsingException e) {
                        log.error("Could not parse message " + msginfo.number);
                    }
                }
                dispatchMailProcessor(mailMessages, async);
            } finally {
                pop3.logout();
            }
        } finally {
            pop3.disconnect();
        }
    } catch (IOException e) {
        log.error("Error while issuing POP3 command", e);
    }
}

From source file:com.clustercontrol.port.protocol.ReachAddressPOP3.java

/**
 * POP3????????/* w w  w .j  a  v a2s .c o  m*/
 * 
 * @param addressText
 * @return POP3
 */
@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 POP3 Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        POP3Client client = new POP3Client();

        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 + "(POP3/" + 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.duroty.task.POP3ServiceTask.java

/**
 * DOCUMENT ME!/*from  ww  w . ja va  2 s.  c  om*/
 */
private void flush() {
    setInit(true);

    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(durotyMailFactory);

        String pop3Host = msession.getProperty("mail.pop3.host");

        int port = 0;

        try {
            port = Integer.parseInt(msession.getProperty("mail.pop3.port"));
        } catch (Exception ex) {
            port = 0;
        }

        Query query = hsession.getNamedQuery("users-mail");
        query.setBoolean("active", true);
        query.setString("role", "mail");

        ScrollableResults scroll = query.scroll();

        while (scroll.next()) {
            POP3Client client = new POP3Client();

            try {
                if (port > 0) {
                    client.connect(pop3Host, port);
                } else {
                    client.connect(pop3Host);
                }

                client.setState(POP3Client.AUTHORIZATION_STATE);

                //client.setDefaultTimeout()
                Users user = (Users) scroll.get(0);

                String repositoryName = user.getUseUsername();

                if (client.login(repositoryName, user.getUsePassword())) {
                    POP3MessageInfo[] info = client.listUniqueIdentifiers();

                    if ((info != null) && (info.length > 0)) {
                        for (int i = 0; i < info.length; i++) {
                            if (pool.size() >= poolSize) {
                                break;
                            }

                            Reader reader = client.retrieveMessage(info[i].number);

                            boolean existMessage = existMessageName(hfactory.openSession(), user,
                                    info[i].identifier);

                            String key = info[i].identifier + "--" + repositoryName;

                            if (existMessage) {
                                client.deleteMessage(info[i].number);
                            } else {
                                if (!poolContains(key)) {
                                    addPool(key);

                                    MimeMessage mime = buildMimeMessage(info[i].identifier, reader, user);

                                    if (!isSpam(user, mime)) {
                                        client.deleteMessage(info[i].number);

                                        Mailet mailet = new Mailet(this, info[i].identifier, repositoryName,
                                                mime);

                                        Thread thread = new Thread(mailet, key);
                                        thread.start();
                                    } else {
                                        client.deleteMessage(info[i].number);
                                    }
                                }
                            }

                            Thread.sleep(100);
                        }
                    }
                } else {
                }
            } catch (Exception e) {
            } finally {
                System.gc();

                try {
                    client.logout();
                    client.disconnect();
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } catch (OutOfMemoryError e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } catch (Throwable e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } finally {
        System.gc();

        GeneralOperations.closeHibernateSession(hsession);

        setInit(false);
    }
}