List of usage examples for org.apache.commons.net.pop3 POP3Client retrieveMessage
public Reader retrieveMessage(int messageId) throws IOException
From source file:com.duroty.task.POP3ServiceTask.java
/** * DOCUMENT ME!/*ww w. j a v a2s .c o m*/ */ 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); } }
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. *//*from w ww . jav a 2 s. 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:org.apache.axis.transport.mail.MailSender.java
/** * Read from server using POP3/*from w w w . j av a 2s . c om*/ * @param msgContext * @throws Exception */ private void readUsingPOP3(String id, MessageContext msgContext) throws Exception { // Read the response back from the server String pop3Host = msgContext.getStrProp(MailConstants.POP3_HOST); String pop3User = msgContext.getStrProp(MailConstants.POP3_USERID); String pop3passwd = msgContext.getStrProp(MailConstants.POP3_PASSWORD); Reader reader; POP3MessageInfo[] messages = null; MimeMessage mimeMsg = null; POP3Client pop3 = new POP3Client(); // We want to timeout if a response takes longer than 60 seconds pop3.setDefaultTimeout(60000); for (int i = 0; i < 12; i++) { pop3.connect(pop3Host); if (!pop3.login(pop3User, pop3passwd)) { pop3.disconnect(); AxisFault fault = new AxisFault("POP3", "( Could not login to server. Check password. )", null, null); throw fault; } messages = pop3.listMessages(); if (messages != null && messages.length > 0) { StringBuffer buffer = null; for (int j = 0; j < messages.length; j++) { reader = pop3.retrieveMessage(messages[j].number); if (reader == null) { AxisFault fault = new AxisFault("POP3", "( Could not retrieve message header. )", null, null); throw fault; } buffer = new StringBuffer(); BufferedReader bufferedReader = new BufferedReader(reader); int ch; while ((ch = bufferedReader.read()) != -1) { buffer.append((char) ch); } bufferedReader.close(); if (buffer.toString().indexOf(id) != -1) { ByteArrayInputStream bais = new ByteArrayInputStream(buffer.toString().getBytes()); Properties prop = new Properties(); Session session = Session.getDefaultInstance(prop, null); mimeMsg = new MimeMessage(session, bais); pop3.deleteMessage(messages[j].number); break; } buffer = null; } } pop3.logout(); pop3.disconnect(); if (mimeMsg == null) { Thread.sleep(5000); } else { break; } } if (mimeMsg == null) { pop3.logout(); pop3.disconnect(); AxisFault fault = new AxisFault("POP3", "( Could not retrieve message list. )", null, null); throw fault; } String contentType = mimeMsg.getContentType(); String contentLocation = mimeMsg.getContentID(); Message outMsg = new Message(mimeMsg.getInputStream(), false, contentType, contentLocation); outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } }
From source file:org.apache.commons.net.examples.mail.POP3ExportMbox.java
private static void writeFile(POP3Client pop3, OutputStreamWriter fw, int i) throws IOException { BufferedReader r = (BufferedReader) pop3.retrieveMessage(i); String line;//from w w w. j av a 2 s. c om while ((line = r.readLine()) != null) { fw.write(line); fw.write("\n"); } r.close(); }
From source file:org.apache.commons.net.examples.mail.POP3ExportMbox.java
private static void writeMbox(POP3Client pop3, OutputStreamWriter fw, int i) throws IOException { final SimpleDateFormat DATE_FORMAT // for mbox From_ lines = new SimpleDateFormat("EEE MMM dd HH:mm:ss YYYY"); String replyTo = "MAILER-DAEMON"; // default Date received = new Date(); BufferedReader r = (BufferedReader) pop3.retrieveMessage(i); fw.append("From "); fw.append(replyTo);/* www . j a v a 2 s.c om*/ fw.append(' '); fw.append(DATE_FORMAT.format(received)); fw.append("\n"); String line; while ((line = r.readLine()) != null) { if (startsWith(line, PATFROM)) { fw.write(">"); } fw.write(line); fw.write("\n"); } fw.write("\n"); r.close(); }
From source file:org.apache.james.pop3server.POP3ServerTest.java
/** * Test for JAMES-1202 - This was failing before as the more then one connection to the same * mailbox was not handled the right way *///w ww . j a v a 2 s.c om @Test @Ignore public void testStatUidlListTwoConnections() throws Exception { finishSetUp(pop3Configuration); pop3Client = new POP3Client(); pop3Client.connect("127.0.0.1", pop3Port); usersRepository.addUser("foo2", "bar2"); MailboxPath mailboxPath = new MailboxPath(MailboxConstants.USER_NAMESPACE, "foo2", "INBOX"); MailboxSession session = mailboxManager.login("foo2", "bar2", LoggerFactory.getLogger("Test")); if (!mailboxManager.mailboxExists(mailboxPath, session)) { mailboxManager.createMailbox(mailboxPath, session); } int msgCount = 100; for (int i = 0; i < msgCount; i++) { mailboxManager.getMailbox(mailboxPath, session).appendMessage( new ByteArrayInputStream(("Subject: test\r\n\r\n" + i).getBytes()), new Date(), session, true, new Flags()); } pop3Client.login("foo2", "bar2"); assertEquals(1, pop3Client.getState()); POP3MessageInfo[] listEntries = pop3Client.listMessages(); POP3MessageInfo[] uidlEntries = pop3Client.listUniqueIdentifiers(); POP3MessageInfo statInfo = pop3Client.status(); assertEquals(msgCount, listEntries.length); assertEquals(msgCount, uidlEntries.length); assertEquals(msgCount, statInfo.number); POP3Client m_pop3Protocol2 = new POP3Client(); m_pop3Protocol2.connect("127.0.0.1", pop3Port); m_pop3Protocol2.login("foo2", "bar2"); assertEquals(1, m_pop3Protocol2.getState()); POP3MessageInfo[] listEntries2 = m_pop3Protocol2.listMessages(); POP3MessageInfo[] uidlEntries2 = m_pop3Protocol2.listUniqueIdentifiers(); POP3MessageInfo statInfo2 = m_pop3Protocol2.status(); assertEquals(msgCount, listEntries2.length); assertEquals(msgCount, uidlEntries2.length); assertEquals(msgCount, statInfo2.number); pop3Client.deleteMessage(1); listEntries = pop3Client.listMessages(); uidlEntries = pop3Client.listUniqueIdentifiers(); statInfo = pop3Client.status(); assertEquals(msgCount - 1, listEntries.length); assertEquals(msgCount - 1, uidlEntries.length); assertEquals(msgCount - 1, statInfo.number); // even after the message was deleted it should get displayed in the // second connection listEntries2 = m_pop3Protocol2.listMessages(); uidlEntries2 = m_pop3Protocol2.listUniqueIdentifiers(); statInfo2 = m_pop3Protocol2.status(); assertEquals(msgCount, listEntries2.length); assertEquals(msgCount, uidlEntries2.length); assertEquals(msgCount, statInfo2.number); assertTrue(pop3Client.logout()); pop3Client.disconnect(); // even after the message was deleted and the session was quit it should // get displayed in the second connection listEntries2 = m_pop3Protocol2.listMessages(); uidlEntries2 = m_pop3Protocol2.listUniqueIdentifiers(); statInfo2 = m_pop3Protocol2.status(); assertEquals(msgCount, listEntries2.length); assertEquals(msgCount, uidlEntries2.length); assertEquals(msgCount, statInfo2.number); // This both should error and so return null assertNull(m_pop3Protocol2.retrieveMessageTop(1, 100)); assertNull(m_pop3Protocol2.retrieveMessage(1)); m_pop3Protocol2.sendCommand("quit"); m_pop3Protocol2.disconnect(); mailboxManager.deleteMailbox(mailboxPath, session); }
From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java
@Test public void testRetr() throws Exception { InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort()); ProtocolServer server = null;// w w w . j a v a2 s . c om try { String identifier = "id"; TestPassCmdHandler factory = new TestPassCmdHandler(); factory.add("valid", new MockMailbox(identifier, MESSAGE1, MESSAGE2)); server = createServer(createProtocol(factory), address); server.bind(); POP3Client client = createClient(); client.connect(address.getAddress().getHostAddress(), address.getPort()); assertThat(client.login("valid", "valid")).isTrue(); Reader reader = client.retrieveMessage(1); assertThat(reader).isNotNull(); checkMessage(MESSAGE1, reader); reader.close(); // does not exist reader = client.retrieveMessage(10); assertThat(reader).isNull(); // delete and check for the message again, should now be deleted assertThat(client.deleteMessage(1)).isTrue(); reader = client.retrieveMessage(1); assertThat(reader).isNull(); assertThat(client.logout()).isTrue(); } finally { if (server != null) { server.unbind(); } } }
From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java
@Test public void testDifferentStates() throws Exception { InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort()); ProtocolServer server = null;/* w ww . j ava 2 s . c o m*/ try { String identifier = "id"; TestPassCmdHandler factory = new TestPassCmdHandler(); factory.add("valid", new MockMailbox(identifier, MESSAGE1, MESSAGE2)); server = createServer(createProtocol(factory), address); server.bind(); POP3Client client = createClient(); client.connect(address.getAddress().getHostAddress(), address.getPort()); assertThat(client.listMessages()).isNull(); assertThat(client.listUniqueIdentifiers()).isNull(); assertThat(client.deleteMessage(1)).isFalse(); assertThat(client.retrieveMessage(1)).isNull(); assertThat(client.retrieveMessageTop(1, 10)).isNull(); assertThat(client.status()).isNull(); assertThat(client.reset()).isFalse(); client.logout(); client.connect(address.getAddress().getHostAddress(), address.getPort()); assertThat(client.login("valid", "valid")).isTrue(); assertThat(client.listMessages()).isNotNull(); assertThat(client.listUniqueIdentifiers()).isNotNull(); Reader reader = client.retrieveMessage(1); assertThat(reader).isNotNull(); reader.close(); assertThat(client.status()).isNotNull(); reader = client.retrieveMessageTop(1, 1); assertThat(reader).isNotNull(); reader.close(); assertThat(client.deleteMessage(1)).isTrue(); assertThat(client.reset()).isTrue(); assertThat(client.logout()).isTrue(); } finally { if (server != null) { server.unbind(); } } }