List of usage examples for javax.mail Folder close
public abstract void close(boolean expunge) throws MessagingException;
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
@Override public AccountSummary fetchAccountSummaryFromStore(MailStoreConfiguration config, String username, String mailAccount, String folder, int start, int max) { Authenticator auth = credentialsProvider.getAuthenticator(); AccountSummary summary;//from www . ja v a 2s. c o m Folder inbox = null; try { // Retrieve user's folder Session session = openMailSession(config, auth); inbox = getUserInbox(session, folder); inbox.open(Folder.READ_ONLY); long startTime = System.currentTimeMillis(); List<EmailMessage> messages = getEmailMessages(inbox, start, max, session); if (log.isDebugEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; int messagesToDisplayCount = messages.size(); log.debug("Finished looking up email messages. Inbox size: " + inbox.getMessageCount() + " Unread message count: " + inbox.getUnreadMessageCount() + " Total elapsed time: " + elapsedTime + "ms " + " Time per message in inbox: " + (inbox.getMessageCount() == 0 ? 0 : (elapsedTime / inbox.getMessageCount())) + "ms" + " Time per displayed message: " + (messagesToDisplayCount == 0 ? 0 : (elapsedTime / messagesToDisplayCount)) + "ms"); } IEmailLinkService linkService = linkServiceRegistry.getEmailLinkService(config.getLinkServiceKey()); String inboxUrl = null; if (linkService != null) { inboxUrl = linkService.getInboxUrl(config); } // Initialize account information with information retrieved from inbox summary = new AccountSummary(inboxUrl, messages, inbox.getUnreadMessageCount(), inbox.getMessageCount(), start, max, isDeleteSupported(inbox), getQuota(inbox)); if (log.isDebugEnabled()) { log.debug("Successfully retrieved email AccountSummary"); } return summary; } catch (MailAuthenticationException mae) { // We used just to allow this exception to percolate up the chain, // but we learned that the entire stack trace gets written to // Catalina.out (by 3rd party code). Since this is a common // occurrence, it causes space issues. return new AccountSummary(mae); } catch (MessagingException me) { log.error("Exception encountered while retrieving account info", me); throw new EmailPreviewException(me); } catch (IOException e) { log.error("Exception encountered while retrieving account info", e); throw new EmailPreviewException(e); } catch (ScanException e) { log.error("Exception encountered while retrieving account info", e); throw new EmailPreviewException(e); } catch (PolicyException e) { log.error("Exception encountered while retrieving account info", e); throw new EmailPreviewException(e); } finally { if (inbox != null) { try { inbox.close(false); } catch (Exception e) { log.warn("Can't close correctly javamail inbox connection"); } try { inbox.getStore().close(); } catch (Exception e) { log.warn("Can't close correctly javamail store connection"); } } } }
From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java
public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName, String mailStorePassword, String notificationType, String fromFilter, String subjectFilter) throws Exception { Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName, mailStorePassword);//from w ww.j av a 2 s . c o m try { // connects to the message store Store store = session.getStore(mailStoreProtocol); store.connect(mailStoreHost, mailStoreUserName, mailStorePassword); logger.info("connected to message store"); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_WRITE); // check if fromFilter is specified List<String> fromFilterList = null; if (StringUtils.isNotBlank(fromFilter)) { String[] fromFilterArray = StringUtils.split(fromFilter, "|"); fromFilterList = Arrays.asList(fromFilterArray); } // check if subjectFilter is specified List<String> subjectFilterList = null; if (StringUtils.isNotBlank(subjectFilter)) { String[] subjectFilterArray = StringUtils.split(subjectFilter, "|"); subjectFilterList = Arrays.asList(subjectFilterArray); } Map<String, Object> context = new HashMap<String, Object>(); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; Address[] fromAddress = msg.getFrom(); String address = fromAddress[0].toString(); String from = extractFromAddress(address); if (StringUtils.isBlank(from)) { logger.warn("From Address is not proper " + from); return; } boolean isValidFrom = isValidMatch(fromFilterList, from); // filter based on fromFilter specified if (null == fromFilterList || isValidFrom) { String subject = msg.getSubject(); boolean isValidSubject = isValidMatch(subjectFilterList, subject); if (null == subjectFilterList || isValidSubject) { String toList = parseAddresses(msg.getRecipients(RecipientType.TO)); String ccList = parseAddresses(msg.getRecipients(RecipientType.CC)); String sentDate = msg.getSentDate().toString(); String messageContent = ""; try { Object content = msg.getContent(); if (content != null) { messageContent = content.toString(); } } catch (Exception ex) { messageContent = "[Error downloading content]"; ex.printStackTrace(); } context.put("from", from); context.put("to", toList); context.put("cc", ccList); context.put("subject", subject); context.put("messagebody", messageContent); context.put("sentdate", sentDate); notificationController.createNotification(notificationType, context); msg.setFlag(Flag.DELETED, true); } else { logger.warn("subjectFilter doesn't match"); } } else { logger.warn("this email originated from " + address + " , which does not match fromAddress specified in the rule, it should be " + fromFilter.toString()); } } // disconnect and delete messages marked as DELETED folderInbox.close(true); store.close(); } catch (NoSuchProviderException ex) { logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex); } catch (MessagingException ex) { logger.error("Could not connect to the message store" + ex); } }
From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java
/** * Loads email properties, reads email messages, * converts their multipart bodies into string, * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports * <p><b> deletes messages// w w w . j a va2 s .c o m * @see #readEmail() * @see #convertToXml(HashSet) * @see ru.retbansk.utils.scheduled.ReplyManager * @return HashSet<DayReport> of the Valid Day Reports */ @Override public HashSet<DayReport> readEmail() throws Exception { Properties prop = loadProperties(); String host = prop.getProperty("host"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); path = prop.getProperty("path"); // Get system properties Properties properties = System.getProperties(); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Get a Store object that implements the specified protocol. Store store = session.getStore("pop3"); // Connect to the current host using the specified username and // password. store.connect(host, user, password); // Create a Folder object corresponding to the given name. Folder folder = store.getFolder("inbox"); // Open the Folder. folder.open(Folder.READ_WRITE); HashSet<DayReport> dayReportSet = new HashSet<DayReport>(); try { // Getting messages from the folder Message[] message = folder.getMessages(); // Reversing the order in the array with the use of Set to make the last one final Collections.reverse(Arrays.asList(message)); // Reading messages. String body; for (int i = 0; i < message.length; i++) { DayReport dayReport = null; dayReport = new DayReport(); dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3")); calendar.setTime(message[i].getSentDate()); dayReport.setCalendar(calendar); dayReport.setSubject(message[i].getSubject()); List<TaskReport> reportList = null; //Release the string from email message body body = ""; Object content = message[i].getContent(); if (content instanceof java.lang.String) { body = (String) content; } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } } } //Put the string (body of email message) and get list of valid reports else send error reportList = new ArrayList<TaskReport>(); reportList = giveValidReports(body, message[i].getSentDate()); //Check for valid day report. To be valid it should have size of reportList > 0. if (reportList.size() > 0) { // adding valid ones to Set dayReport.setReportList(reportList); dayReportSet.add(dayReport); } else { // This message doesn't have valid reports. Sending an error reply. logger.info("Invalid Day Report detected. Sending an error reply"); ReplyManager man = new ReplyManagerSimpleImpl(); man.sendError(dayReport); } // Delete message message[i].setFlag(Flags.Flag.DELETED, true); } } finally { // true tells the mail server to expunge deleted messages. folder.close(true); store.close(); } return dayReportSet; }
From source file:net.wastl.webmail.server.WebMailSession.java
/** Change the Flags of the messages the user selected. /*from ww w. j av a2 s .c o m*/ */ public void setFlags(String folderhash, HTTPRequestHeader head) throws MessagingException { if (head.isContentSet("copymovemsgs") && head.getContent("COPYMOVE").equals("COPY")) { copyMoveMessage(folderhash, head.getContent("TO"), head, false); } else if (head.isContentSet("copymovemsgs") && head.getContent("COPYMOVE").equals("MOVE")) { copyMoveMessage(folderhash, head.getContent("TO"), head, true); } else if (head.isContentSet("flagmsgs")) { log.debug("setting message flags"); Folder folder = getFolder(folderhash); //log.debug("Processing Request Header..."); /* Get selected messages */ int msgs[] = getSelectedMessages(head, folder.getMessageCount()); //log.debug("get flags..."); /* Get selected flags */ Flags fl = new Flags(Flags.Flag.USER); if (head.getContent("MESSAGE FLAG").equals("DELETED")) { fl = new Flags(Flags.Flag.DELETED); if (need_expunge_folders == null) { need_expunge_folders = new Vector<String>(); } need_expunge_folders.addElement(folderhash); } else if (head.getContent("MESSAGE FLAG").equals("SEEN")) { fl = new Flags(Flags.Flag.SEEN); } else if (head.getContent("MESSAGE FLAG").equals("RECENT")) { fl = new Flags(Flags.Flag.RECENT); } else if (head.getContent("MESSAGE FLAG").equals("ANSWERED")) { fl = new Flags(Flags.Flag.ANSWERED); } else if (head.getContent("MESSAGE FLAG").equals("DRAFT")) { fl = new Flags(Flags.Flag.DRAFT); } boolean value = true; if (head.getContent("MARK").equals("UNMARK")) { value = false; } //log.debug("Done!"); //log.debug("Setting flags..."); if (user.wantsSetFlags()) { if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) { folder.close(false); folder.open(Folder.READ_WRITE); } else if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } folder.setFlags(msgs, fl, value); if (user.getBoolVar("autoexpunge")) { folder.close(true); if (need_expunge_folders != null) { need_expunge_folders.removeElement(folderhash); } } else { folder.close(false); } } folder.open(Folder.READ_WRITE); refreshFolderInformation(folderhash); } }
From source file:com.seleniumtests.connectors.mails.ImapClient.java
/** * get list of all emails in folder// w w w.jav a 2s. c o m * * @param folderName folder to read * @param firstMessageTime date from which we should get messages * @param firstMessageIndex index of the firste message to find * @throws MessagingException * @throws IOException */ @Override public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime) throws MessagingException, IOException { if (folderName == null) { throw new MessagingException("folder ne doit pas tre vide"); } // Get folder Folder folder = store.getFolder(folderName); folder.open(Folder.READ_ONLY); // Get directory Message[] messages = folder.getMessages(); List<Message> preFilteredMessages = new ArrayList<>(); final LocalDateTime firstTime = firstMessageTime; // on filtre les message en fonction du mode de recherche if (searchMode == SearchMode.BY_INDEX || firstTime == null) { for (int i = firstMessageIndex, n = messages.length; i < n; i++) { preFilteredMessages.add(messages[i]); } } else { preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() { private static final long serialVersionUID = 1L; @Override public boolean match(Message msg) { try { return !msg.getReceivedDate() .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant())); } catch (MessagingException e) { return false; } } })); } List<Email> filteredEmails = new ArrayList<>(); lastMessageIndex = messages.length; for (Message message : preFilteredMessages) { String contentType = ""; try { contentType = message.getContentType(); } catch (MessagingException e) { MimeMessage msg = (MimeMessage) message; message = new MimeMessage(msg); contentType = message.getContentType(); } // decode content String messageContent = ""; List<String> attachments = new ArrayList<>(); if (contentType.toLowerCase().contains("text/html")) { messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString()); } else if (contentType.toLowerCase().contains("multipart/")) { List<BodyPart> partList = getMessageParts((Multipart) message.getContent()); // store content in list for (BodyPart part : partList) { String partContentType = part.getContentType().toLowerCase(); if (partContentType.contains("text/html")) { messageContent = messageContent .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString())); } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) { messageContent = messageContent.concat((String) part.getContent().toString()); } else if (partContentType.contains("image") || partContentType.contains("application/") || partContentType.contains("text/x-vcard")) { if (part.getFileName() != null) { attachments.add(part.getFileName()); } else { attachments.add(part.getDescription()); } } else { logger.debug("type: " + part.getContentType()); } } } // create a new email filteredEmails.add(new Email(message.getSubject(), messageContent, "", message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), attachments)); } folder.close(false); return filteredEmails; }
From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java
/** * {@inheritDoc}//from w ww.ja v a 2s .com */ @Override public SampleResult sample(Entry e) { SampleResult parent = new SampleResult(); boolean isOK = false; // Did sample succeed? final boolean deleteMessages = getDeleteMessages(); final String serverProtocol = getServerType(); parent.setSampleLabel(getName()); String samplerString = toString(); parent.setSamplerData(samplerString); /* * Perform the sampling */ parent.sampleStart(); // Start timing try { // Create empty properties Properties props = new Properties(); if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$ if (isEnforceStartTLS()) { // Requires JavaMail 1.4.2+ props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$ } } if (isTrustAllCerts()) { if (isUseSSL()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } else if (isUseLocalTrustStore()) { File truststore = new File(getTrustStoreToUse()); log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse()); log.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (isUseSSL()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } // Get session Session session = Session.getInstance(props, null); // Get the store Store store = session.getStore(serverProtocol); store.connect(getServer(), getPortAsInt(), getUserName(), getPassword()); // Get folder Folder folder = store.getFolder(getFolder()); if (deleteMessages) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } final int messageTotal = folder.getMessageCount(); int n = getNumMessages(); if (n == ALL_MESSAGES || n > messageTotal) { n = messageTotal; } // Get directory Message[] messages = folder.getMessages(1, n); StringBuilder pdata = new StringBuilder(); pdata.append(messages.length); pdata.append(" messages found\n"); parent.setResponseData(pdata.toString(), null); parent.setDataType(SampleResult.TEXT); parent.setContentType("text/plain"); // $NON-NLS-1$ final boolean headerOnly = getHeaderOnly(); busy = true; for (Message message : messages) { StringBuilder cdata = new StringBuilder(); SampleResult child = new SampleResult(); child.sampleStart(); cdata.append("Message "); // $NON-NLS-1$ cdata.append(message.getMessageNumber()); child.setSampleLabel(cdata.toString()); child.setSamplerData(cdata.toString()); cdata.setLength(0); final String contentType = message.getContentType(); child.setContentType(contentType);// Store the content-type child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default child.setEncodingAndType(contentType);// Parse the content-type if (isStoreMimeMessage()) { // Don't save headers - they are already in the raw message ByteArrayOutputStream bout = new ByteArrayOutputStream(); message.writeTo(bout); child.setResponseData(bout.toByteArray()); // Save raw message child.setDataType(SampleResult.TEXT); } else { @SuppressWarnings("unchecked") // Javadoc for the API says this is OK Enumeration<Header> hdrs = message.getAllHeaders(); while (hdrs.hasMoreElements()) { Header hdr = hdrs.nextElement(); String value = hdr.getValue(); try { value = MimeUtility.decodeText(value); } catch (UnsupportedEncodingException uce) { // ignored } cdata.append(hdr.getName()).append(": ").append(value).append("\n"); } child.setResponseHeaders(cdata.toString()); cdata.setLength(0); if (!headerOnly) { appendMessageData(child, message); } } if (deleteMessages) { message.setFlag(Flags.Flag.DELETED, true); } child.setResponseOK(); if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called. child.sampleEnd(); } parent.addSubResult(child); } // Close connection folder.close(true); store.close(); parent.setResponseCodeOK(); parent.setResponseMessageOK(); isOK = true; } catch (NoClassDefFoundError | IOException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString()); } catch (MessagingException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$ } finally { busy = false; } if (parent.getEndTime() == 0) {// not been set by any child samples parent.sampleEnd(); } parent.setSuccessful(isOK); return parent; }
From source file:org.eurekastreams.server.service.email.ImapEmailIngester.java
/** * Ingests email from a mailbox.//from w w w . j av a 2 s. c om */ public void execute() { // get message store Store store; try { long startTime = System.nanoTime(); store = storeFactory.getStore(); log.debug("Connected to mail store in {}ns", System.nanoTime() - startTime); } catch (MessagingException ex) { log.error("Error getting message store.", ex); return; } try { // get folders Folder inputFolder = store.getFolder(inputFolderName); if (!inputFolder.exists()) { log.error("Input folder {} does not exist.", inputFolderName); return; } Folder successFolder = null; if (StringUtils.isNotBlank(successFolderName)) { successFolder = store.getFolder(successFolderName); if (!successFolder.exists()) { log.error("Success folder {} does not exist.", successFolderName); return; } } Folder discardFolder = null; if (StringUtils.isNotBlank(discardFolderName)) { discardFolder = store.getFolder(discardFolderName); if (!discardFolder.exists()) { log.error("Discard folder {} does not exist.", discardFolderName); return; } } Folder errorFolder = null; if (StringUtils.isNotBlank(errorFolderName)) { errorFolder = store.getFolder(errorFolderName); if (!errorFolder.exists()) { log.error("Error folder {} does not exist.", errorFolderName); return; } } inputFolder.open(Folder.READ_WRITE); // fetch messages // Note: Not preloading CONTENT_INFO. For some reason, preloading the content info (IMAP BODYSTRUCTURE) // causes the call to getContent to return empty. (As if there was a bug where getContent saw the cached // body structure and thought that the content itself was cached, but I'd think a bug like that would have // been found by many people and fixed long ago, so I'm assuming it's something else.) FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); Message[] msgs = inputFolder.getMessages(); inputFolder.fetch(msgs, fp); log.debug("About to process {} messages", msgs.length); // process each message if (msgs.length > 0) { List<Message> successMessages = new ArrayList<Message>(); List<Message> errorMessages = new ArrayList<Message>(); List<Message> discardMessages = new ArrayList<Message>(); List<Message> responseMessages = new ArrayList<Message>(); for (int i = 0; i < msgs.length; i++) { Message message = msgs[i]; try { boolean processed = messageProcessor.execute(message, responseMessages); (processed ? successMessages : discardMessages).add(message); } catch (Exception ex) { log.error("Failed to process email message.", ex); errorMessages.add(message); } } // send response messages for (Message responseMessage : responseMessages) { emailerFactory.sendMail(responseMessage); } // move and purge messages if (successFolder != null && !successMessages.isEmpty()) { inputFolder.copyMessages(successMessages.toArray(new Message[successMessages.size()]), successFolder); } if (discardFolder != null && !discardMessages.isEmpty()) { inputFolder.copyMessages(discardMessages.toArray(new Message[discardMessages.size()]), discardFolder); } if (errorFolder != null && !errorMessages.isEmpty()) { inputFolder.copyMessages(errorMessages.toArray(new Message[errorMessages.size()]), errorFolder); } for (int i = 0; i < msgs.length; i++) { msgs[i].setFlag(Flag.DELETED, true); } log.info("{} messages processed: {} successful, {} discarded, {} failed.", new Object[] { msgs.length, successMessages.size(), discardMessages.size(), errorMessages.size() }); } // close folder inputFolder.close(true); } catch (MessagingException ex) { log.error("Error ingesting email.", ex); } catch (Exception ex) { log.error("Error ingesting email.", ex); } finally { // close store try { store.close(); } catch (MessagingException ex) { log.error("Error closing message store.", ex); } } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Construct the folder subtree for the given folder and append it to * xml_parent.// www.ja va2 s. c o m * * N.b. this method does not necessarily create a new XML Folder Element. * If called with subscribed_only and the target Folder (and in some * cases its descendants) are not subscribed, no Element will be created * and 0 will be returned. * <P> * Pop servers don't support nesting at all, so you'll just get a single * level out of this method. * <P> * There is a critical subscribed_only difference in behavior between * Maildir and mbox type mail servers. * Maildir folders are all HOLDS_MESSAGES, whether empty or not, and * these folders have a subscribed attribute which the user can set, * and which we honor. * mbox folders, on the other hand, have no subscribed attribute for * their !HOLDS_MESSAGE folders, so we must recurse to all of the * descendant HOLDS_MESSAGE folders to see if we should show. * * @param folder the folder where we begin * @param xml_parent XML Element where the gathered information will be * appended * @param subscribed_only Only add 'subscribed' folders * @param doCount Whether to generate message counts for Elements * corresponding to HOLDS_MESSAGE folders. * @returns maximum depth of the folder tree (needed to calculate the * necessary columns in a table). Returns 0 if no XML elements added. */ protected int getFolderTree(Folder folder, Element xml_parent, boolean subscribed_only, boolean doCount) { int generatedDepth = 0; int folderType; Element xml_folder; try { folderType = folder.getType(); } catch (MessagingException ex) { log.error("Can't get enough info from server to even make Gui node", ex); xml_parent.setAttribute("error", "For child '" + folder.getName() + ": " + ex.getMessage()); return 0; } boolean holds_folders = (folderType & Folder.HOLDS_FOLDERS) != 0; boolean holds_messages = (folderType & Folder.HOLDS_MESSAGES) != 0; // Sanity check: if ((!holds_folders) && !holds_messages) { log.fatal("Folder can hold neither folders nor messages: " + folder.getFullName()); throw new RuntimeException("Folder can hold neither folders nor messages: " + folder.getFullName()); } if (subscribed_only && holds_messages && !folder.isSubscribed()) return generatedDepth; // Return right away and save a LOT OF WORK // N.b. we honor folder.isSubscribed() only for holds_message // folders. That means all Maildir server folders, and all // mbox server folders except for mbox directories. In this // last case, we must recurse to determine whether to show folder. String id = generateFolderHash(folder); xml_folder = model.createFolder(id, folder.getName(), holds_folders, holds_messages); // XMLUserModel.createFolder() declares no throws. If any Exceptions // are expected from it, move the statement above into the try block. // The xml_folder Element here will be orphaned and GC'd if we don't // appendChild (in which case we return 0). if (doCount && holds_messages) try { // this folder will definitely be added! /* This folder can contain messages */ Element messagelist = model.createMessageList(); int total_messages = folder.getMessageCount(); int new_messages = folder.getNewMessageCount(); if (total_messages == -1 || new_messages == -1 || !folder.isOpen()) { folder.open(Folder.READ_ONLY); total_messages = folder.getMessageCount(); new_messages = folder.getNewMessageCount(); } if (folder.isOpen()) folder.close(false); messagelist.setAttribute("total", total_messages + ""); messagelist.setAttribute("new", new_messages + ""); log.debug("Counted " + new_messages + '/' + total_messages + " for folder " + folder.getFullName()); xml_folder.appendChild(messagelist); } catch (MessagingException ex) { log.warn("Failed to count messages in folder '" + folder.getFullName() + "'", ex); xml_folder.setAttribute("error", ex.getMessage()); } int descendantDepth = 0; if (holds_folders) try { Set<String> fullNameSet = new HashSet<String>(); /* Recursively add subfolders to the XML model */ // DO NOT USE listSubscribed(), because with !HOLDS_MESSAGE // folders, that skips non-Message Folders which may contain // subscribed descendants! for (Folder f : folder.list()) { if (!fullNameSet.add(f.getFullName())) { log.warn("Skipping duplicate subfolder returned by mail" + " server: " + f.getFullName()); continue; } if (subscribed_only && (f.getType() & Folder.HOLDS_MESSAGES) != 0 && !f.isSubscribed()) continue; /* If we recursed here, the getFolderTree() would * just return 0 and no harm done. * Just helping performance by preventing a recursion * here. * For comment on the logic here, see the same test * towards the top of this method (before recursion). */ int depth = getFolderTree(f, xml_folder, subscribed_only, doCount); if (depth > descendantDepth) descendantDepth = depth; } generatedDepth += descendantDepth; } catch (MessagingException ex) { xml_folder.setAttribute("error", ex.getMessage()); } // We've already validated that if subscribed_only and holds_message // then folder is subcribed. Also verified either holds_m or holds_f. // Only have to check the !holds_message case. if (subscribed_only && (!holds_messages) && descendantDepth < 1) { xml_folder = null; // Unnecessary, but may encourage GC return generatedDepth; } /* We ALWAYS return only subscribed folders except for these two * distinct cases: */ xml_folder.setAttribute("subscribed", ((holds_messages && !folder.isSubscribed()) || ((!holds_messages) && descendantDepth < 1)) ? "false" : "true"); // N.b. our Element's "subscribed" element does not correspond 1:1 // to Folder.isSubscribed(), since non-message-holding Folders have // no "subscribed" attribute. folders.put(id, folder); xml_parent.appendChild(xml_folder); generatedDepth++; // Add the count for xml_folder return generatedDepth; }
From source file:org.nuclos.server.ruleengine.RuleInterface.java
/** * * @param pop3Host// w w w. jav a 2s. c o m * @param pop3Port * @param pop3User * @param pop3Password * @param remove * @return * @throws NuclosFatalRuleException */ public List<NuclosMail> getMails(String pop3Host, String pop3Port, final String pop3User, final String pop3Password, boolean remove) throws NuclosFatalRuleException { try { Properties properties = new Properties(); properties.setProperty("mail.pop3.host", pop3Host); properties.setProperty("mail.pop3.port", pop3Port); properties.setProperty("mail.pop3.auth", "true"); properties.setProperty("mail.pop3.socketFactory.class", "javax.net.DefaultSocketFactory"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(pop3User, pop3Password); } }); session.setDebug(true); Store store = session.getStore("pop3"); store.connect(); Folder folder = store.getFolder("INBOX"); if (remove) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } List<NuclosMail> result = new ArrayList<NuclosMail>(); Message message[] = folder.getMessages(); for (int i = 0; i < message.length; i++) { Message m = message[i]; NuclosMail mail = new NuclosMail(); logger.debug("Received mail: From: " + Arrays.toString(m.getFrom()) + "; To: " + Arrays.toString(m.getAllRecipients()) + "; ContentType: " + m.getContentType() + "; Subject: " + m.getSubject() + "; Sent: " + m.getSentDate()); Address[] senders = m.getFrom(); if (senders.length == 1 && senders[0] instanceof InternetAddress) { mail.setFrom(((InternetAddress) senders[0]).getAddress()); } else { mail.setFrom(Arrays.toString(m.getFrom())); } mail.setTo(Arrays.toString(m.getRecipients(RecipientType.TO))); mail.setSubject(m.getSubject()); if (m.isMimeType("text/plain")) { mail.setMessage((String) m.getContent()); } else { Multipart mp = (Multipart) m.getContent(); for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); MimeBodyPart mimePart = (MimeBodyPart) part; logger.debug( "Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType()); if (disposition == null && (mimePart.isMimeType("text/plain") || mimePart.isMimeType("text/html"))) { mail.setMessage((String) mimePart.getDataHandler().getContent()); } } getAttachments(mp, mail); } result.add(mail); if (remove) { m.setFlag(Flags.Flag.DELETED, true); } } if (remove) { folder.close(true); } else { folder.close(false); } store.close(); return result; } catch (Exception e) { throw new NuclosFatalRuleException(e); } }
From source file:org.nuxeo.ecm.platform.mail.utils.MailCoreHelper.java
protected static void doCheckMail(DocumentModel currentMailFolder, CoreSession coreSession) throws MessagingException { String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME); String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME); if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) { mailService = getMailService();//from w w w . j av a 2s. com MessageActionPipe pipe = mailService.getPipe(PIPE_NAME); Visitor visitor = new Visitor(pipe); Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader()); // initialize context ExecutionContext initialExecutionContext = new ExecutionContext(); initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService()); initialExecutionContext.put(PARENT_PATH_KEY, currentMailFolder.getPathAsString()); initialExecutionContext.put(CORE_SESSION_KEY, coreSession); initialExecutionContext.put(LEAVE_ON_SERVER_KEY, Boolean.TRUE); // TODO should be an attribute in 'protocol' // schema Folder rootFolder = null; Store store = null; try { String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME); initialExecutionContext.put(PROTOCOL_TYPE_KEY, protocolType); // log.debug(PROTOCOL_TYPE_KEY + ": " + (String) initialExecutionContext.get(PROTOCOL_TYPE_KEY)); String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME); String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME); Boolean socketFactoryFallback = (Boolean) currentMailFolder .getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME); String socketFactoryPort = (String) currentMailFolder .getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME); Boolean starttlsEnable = (Boolean) currentMailFolder .getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME); String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME); Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME); long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT : emailsLimit.longValue(); String imapDebug = Framework.getProperty(IMAP_DEBUG, "false"); Properties properties = new Properties(); properties.put("mail.store.protocol", protocolType); // properties.put("mail.host", host); // Is IMAP connection if (IMAP.equals(protocolType)) { properties.put("mail.imap.host", host); properties.put("mail.imap.port", port); properties.put("mail.imap.starttls.enable", starttlsEnable.toString()); properties.put("mail.imap.debug", imapDebug); properties.put("mail.imap.partialfetch", "false"); } else if (IMAPS.equals(protocolType)) { properties.put("mail.imaps.host", host); properties.put("mail.imaps.port", port); properties.put("mail.imaps.starttls.enable", starttlsEnable.toString()); properties.put("mail.imaps.ssl.protocols", sslProtocols); properties.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.imaps.socketFactory.fallback", socketFactoryFallback.toString()); properties.put("mail.imaps.socketFactory.port", socketFactoryPort); properties.put("mail.imap.partialfetch", "false"); properties.put("mail.imaps.partialfetch", "false"); } else if (POP3S.equals(protocolType)) { properties.put("mail.pop3s.host", host); properties.put("mail.pop3s.port", port); properties.put("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.pop3s.socketFactory.fallback", socketFactoryFallback.toString()); properties.put("mail.pop3s.socketFactory.port", socketFactoryPort); properties.put("mail.pop3s.ssl.protocols", sslProtocols); } else { // Is POP3 connection properties.put("mail.pop3.host", host); properties.put("mail.pop3.port", port); } properties.put("user", email); properties.put("password", password); Session session = Session.getInstance(properties); store = session.getStore(); store.connect(email, password); String folderName = INBOX; // TODO should be an attribute in 'protocol' schema rootFolder = store.getFolder(folderName); // need RW access to update message flags rootFolder.open(Folder.READ_WRITE); Message[] allMessages = rootFolder.getMessages(); // VDU log.debug("nbr of messages in folder:" + allMessages.length); FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(FetchProfile.Item.FLAGS); fetchProfile.add(FetchProfile.Item.ENVELOPE); fetchProfile.add(FetchProfile.Item.CONTENT_INFO); fetchProfile.add("Message-ID"); fetchProfile.add("Content-Transfer-Encoding"); rootFolder.fetch(allMessages, fetchProfile); if (rootFolder instanceof IMAPFolder) { // ((IMAPFolder)rootFolder).doCommand(FetchProfile) } List<Message> unreadMessagesList = new ArrayList<Message>(); for (Message message : allMessages) { Flags flags = message.getFlags(); int unreadMessagesListSize = unreadMessagesList.size(); if (flags != null && !flags.contains(Flag.SEEN) && unreadMessagesListSize < emailsLimitLongValue) { unreadMessagesList.add(message); if (unreadMessagesListSize == emailsLimitLongValue - 1) { break; } } } Message[] unreadMessagesArray = unreadMessagesList.toArray(new Message[unreadMessagesList.size()]); // perform email import visitor.visit(unreadMessagesArray, initialExecutionContext); // perform flag update globally Flags flags = new Flags(); flags.add(Flag.SEEN); boolean leaveOnServer = (Boolean) initialExecutionContext.get(LEAVE_ON_SERVER_KEY); if ((IMAP.equals(protocolType) || IMAPS.equals(protocolType)) && leaveOnServer) { flags.add(Flag.SEEN); } else { flags.add(Flag.DELETED); } rootFolder.setFlags(unreadMessagesArray, flags, true); } finally { if (rootFolder != null && rootFolder.isOpen()) { rootFolder.close(true); } if (store != null) { store.close(); } } } }