📄 pop3driver.java
字号:
+ "' found", e); } try { store.connect(); if (!this.isConnected) { // Avoid too many logging output log.info("Successfully contacted POP3 server '" + getUrlWithoutPassword() + "', we poll every " + this.pollingInterval + " milliseconds for emails."); this.isConnected = true; } return store; } catch (MessagingException e) { /* if (e.getNextException() != null && (e.getNextException() instanceof ConnectException)) { //e.detailMessage=="Connect failed"; log.warning("POP3 server is down" + e.getMessage()); } */ if (this.isConnected) { // Avoid too many logging output log.warning("No POP3 server '" + this.pop3Url + "' found, we poll every " + this.pollingInterval + " milliseconds again:" + e.toString()); this.isConnected = false; } if (e instanceof javax.mail.AuthenticationFailedException) throw new XmlBlasterException(this.glob, ErrorCode.RESOURCE_CONFIGURATION_CONNECT, Pop3Driver.class .getName(), "The POP3 server '" + this.pop3Url + "' is not available", e); else throw new XmlBlasterException(this.glob, ErrorCode.RESOURCE_CONFIGURATION_CONNECT, Pop3Driver.class .getName(), "The POP3 server '" + getUrlWithoutPassword() + "' is not available", e); } } /** * Read messages from mail server with POP3. * <p> * Convenience method which returns the most important fields only * </p> * * @param clear * If CLEAR_MESSAGES=true the messages are destroyed on the server * @return Never null */ public EmailData[] readInbox(boolean clear) throws XmlBlasterException { // if (isShutdown()) Does it recover automatically after a shutdown? // throw new XmlBlasterException(glob, ErrorCode.INTERNAL_ILLEGALSTATE, // Pop3Driver.class.getName(), "The plugin is shutdown"); Store store = null; Folder inbox = null; try { store = getStore(); Folder root = store.getDefaultFolder(); inbox = root.getFolder(POP3_FOLDER); inbox.open(Folder.READ_WRITE); Message[] msgs = inbox.getMessages(); if (msgs == null) msgs = new Message[0]; EmailData[] datas = new EmailData[msgs.length]; for (int i = 0; i < msgs.length; i++) { log.fine("Reading message #" + (i+1) + "/" + msgs.length + " from INBOX"); MimeMessage msg = (MimeMessage) msgs[i]; if (clear) msg.setFlag(Flags.Flag.DELETED, true); Address[] froms = msg.getFrom(); String from = (froms != null && froms.length > 0) ? froms[0] .toString() : ""; Address[] arr = msg.getAllRecipients(); if (arr == null) arr = new Address[0]; String[] recips = new String[arr.length]; for (int j = 0; j < arr.length; j++) recips[j] = arr[j].toString(); //String content = retrieveContent(msg); // Would sometimes deliver an attachment String content = ""; datas[i] = new EmailData(recips, from, msg.getSubject(), content); datas[i].setSentDate(msg.getSentDate()); datas[i].setReplyTo((InternetAddress[])msg.getReplyTo()); /* String[] expires = msg.getHeader(EmailData.EXPIRES_HEADER); // "X-xmlBlaster-ExpiryDate: 2005-12-24 16:45:55.322" if (expires != null && expires.length > 0) { // expires[0]="2005-12-24 16:45:55.322" String value = expires[0].trim(); try { datas[i].setExpiryTime(java.sql.Timestamp.valueOf(value)); // Change to IsoDateParser with UTC! } catch (Throwable e) { System.err.println("xmlBlaster Pop3Driver.java: Ignoring illegal email header '" + expires[0] + "'"); e.printStackTrace(); } } else { */ // Expires: Thu, 15 Dec 2005 21:45:01 +0100 (CET) String[] expires = msg.getHeader(EmailData.EXPIRES_HEADER_RFC2156); if (expires != null && expires.length > 0) { // Date: Thu, 17 Nov 2005 16:45:12 +0100 (CET) String value = expires[0].trim(); try { datas[i].setExpiryTime(MailUtil.dateTimeTS(value)); } catch (Throwable e) { System.err.println("xmlBlaster Pop3Driver.java: Ignoring illegal email header '" + expires[0] + "'"); e.printStackTrace(); } } //} datas[i].setAttachments(MailUtil.accessAttachments(msg)); } return datas; } catch (MessagingException e) { throw new XmlBlasterException(this.glob, ErrorCode.RESOURCE_CONFIGURATION, Pop3Driver.class.getName(), "Problems to read POP3 email from '" + getUrlWithoutPassword() + "'", e); } finally { try { if (inbox != null) { inbox.close(true); inbox = null; } } catch (Exception e) { // MessagingException, IOException log.warning("Ignoring inbox close problem: " + e.toString()); } try { if (store != null) { store.close(); store = null; } } catch (Exception e) { // MessagingException, IOException log.warning("Ignoring store close problem: " + e.toString()); } } } /** * @return Syntax is "pop3://user:password@host:port/INBOX" */ public String getPop3Url() { return this.pop3Url; } /** * @param pop3Url * Syntax is "pop3://user:password@host:port/INBOX" */ public void setPop3Url(String pop3Url) { this.pop3Url = pop3Url; } /** * @return Returns the pollingInterval. */ public long getPollingInterval() { return this.pollingInterval; } /** * @param pollingInterval * The timeout in milliseconds. */ public void setPollingInterval(long pollingInterval) { this.pollingInterval = pollingInterval; } /** * Get content text. * * @param part * the MimePart to check for content * @return The retrieved string * @throws MessagingException * @throws IOException */ protected String retrieveContent(MimePart part) throws MessagingException, IOException { if (part.isMimeType("text/plain")) { return part.getContent().toString(); } else if (part.isMimeType("text/html")) { return part.getContent().toString(); } else if (part.isMimeType("multipart/mixed")) { // Find the first body part, and determine what to do then. MimeMultipart multipart = (MimeMultipart) part.getContent(); MimeBodyPart firstPart = (MimeBodyPart) multipart.getBodyPart(0); return retrieveContent(firstPart); } else if (part.isMimeType("multipart/alternative")) { MimeMultipart multipart = (MimeMultipart) part.getContent(); int count = multipart.getCount(); for (int index = 0; index < count; index++) { MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart .getBodyPart(index); return retrieveContent(mimeBodyPart); } return ""; } else { return ""; } } /** * Activate xmlBlaster access through this protocol. Triggers an immediate * POP3 access and starts polling thereafter */ public void activate() throws Exception { log.fine("Entering activate()"); try { this.timeoutHandle = this.timeout.addOrRefreshTimeoutListener(this, 0, null, this.timeoutHandle); } catch (XmlBlasterException e) { log.severe("Activating timeout listener failed: " + e.getMessage()); throw new Exception("Activating timeout listener failed: " + e.getMessage()); } } public boolean isActive() { return this.timeoutHandle != null; } /** * Deactivate xmlBlaster access (standby), no clients can connect. */ public void deActivate() { log.fine("Entering deActivate()"); if (this.timeout != null) { this.timeout.removeTimeoutListener(this.timeoutHandle); this.timeoutHandle = null; } } /** * Halt the plugin. */ public synchronized void shutdown() { if (this.session != null) { log.info("Shutting down POP3 mail client, removing listeners"); deActivate(); synchronized (this.listeners) { this.listeners.clear(); } if (this.glob != null) this.glob.unregisterMBean(this.mbeanHandle); this.session = null; } } public boolean isShutdown() { return this.session == null; } /** * JMX * @return a human readable usage help string */ public java.lang.String usage() { return "The pop3Url has the syntax 'pop3://user:password@host:port/INBOX'" + "\nCalling shutdown destroys the service (you can't start it again)" + Global.getJmxUsageLinkInfo(this.getClass().getName(), null); } /** * @return A link for JMX usage */ public java.lang.String getUsageUrl() { return Global.getJavadocUrl(this.getClass().getName(), null); } /* dummy to have a copy/paste functionality in jconsole */ public void setUsageUrl(java.lang.String url) { } /** * @return Returns the holdbackExpireTimeout. */ public long getHoldbackExpireTimeout() { return this.holdbackExpireTimeout; } /** * @param holdbackExpireTimeout The holdbackExpireTimeout to set. */ public void setHoldbackExpireTimeout(long holdbackExpireTimeout) { this.holdbackExpireTimeout = holdbackExpireTimeout; } public int getNumberOfHoldbackEmails() { return this.holdbackMap.size(); } /** * java -Dmail.pop3.url=pop3://blue:blue@localhost:110/INBOX * org.xmlBlaster.util.protocol.email.Pop3Driver -receivePolling true -clearMessages false * <p> * * @see #setSessionProperties(Properties) for other properties */ public static void main(String[] args) { Global glob = new Global(args); boolean receivePolling = glob.getProperty().get("receivePolling", false); boolean clearMessages = glob.getProperty().get("clearMessages", Pop3Driver.CLEAR_MESSAGES); boolean interactive = glob.getProperty().get("interactive", true); long pollingInterval = glob.getProperty().get("pop3PollingInterval", 2000L); Pop3Driver pop3Client = new Pop3Driver(); try { final boolean debug = false; // Here we create the pop3Client Session manually without a JNDI lookup Properties props = System.getProperties(); props.put("pop3Client.debug", "" + debug); pop3Client.setSessionProperties(props, glob, null); System.out.println("Reading POP3 messages clearMessages=" + clearMessages); while (true) { long start = System.currentTimeMillis(); EmailData[] msgs = pop3Client.readInbox(clearMessages); long diff = System.currentTimeMillis() - start; java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime()); for (int i = 0; i < msgs.length; i++) { System.out.println(date.toString() + "\n" + msgs[i].toXml(true)); } if (msgs.length == 0) { System.out.println("[" + pop3Client.getPop3Url() + "] No mails over POP3 found (" + diff + " millis)"); } else { System.out.println("[" + pop3Client.getPop3Url() + " "+date.toString()+"] Got "+msgs.length +" mails (" + diff + " millis)"); } if (!receivePolling) break; if (interactive) { int ch = Global.waitOnKeyboardHit("[" + pop3Client.getPop3Url() + "] Hit a key for next polling ('q' to quit) >"); if (ch == 'q') break; } else Thread.sleep(pollingInterval); } } catch (Exception e) { e.printStackTrace(); System.out.println(pop3Client.getPop3Url() + ": pop3Client failed: " + e.toString()); } finally { if (pop3Client != null) pop3Client.shutdown(); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -