List of usage examples for javax.mail Folder getUnreadMessageCount
public synchronized int getUnreadMessageCount() throws MessagingException
From source file:net.prhin.mailman.MailMan.java
public static void main(String[] args) { Properties props = new Properties(); props.setProperty(resourceBundle.getString("mailman.mail.store"), resourceBundle.getString("mailman.protocol")); Session session = Session.getInstance(props); try {//from w w w . j a v a2 s. c o m Store store = session.getStore(); store.connect(resourceBundle.getString("mailman.host"), resourceBundle.getString("mailman.user"), resourceBundle.getString("mailman.password")); Folder inbox = store.getFolder(resourceBundle.getString("mailman.folder")); inbox.open(Folder.READ_ONLY); inbox.getUnreadMessageCount(); Message[] messages = inbox.getMessages(); for (int i = 0; i <= messages.length / 2; i++) { Message tmpMessage = messages[i]; Multipart multipart = (Multipart) tmpMessage.getContent(); System.out.println("Multipart count: " + multipart.getCount()); for (int j = 0; j < multipart.getCount(); j++) { BodyPart bodyPart = multipart.getBodyPart(j); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) { if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) { MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent(); for (int k = 0; k < mimeMultipart.getCount(); k++) { if (mimeMultipart.getBodyPart(k).getFileName() != null) { printFileContents(mimeMultipart.getBodyPart(k)); } } } } else { printFileContents(bodyPart); } } } inbox.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:folderlist.java
static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception { System.out.println(tab + "Name: " + folder.getName()); System.out.println(tab + "Full Name: " + folder.getFullName()); System.out.println(tab + "URL: " + folder.getURLName()); if (verbose) { if (!folder.isSubscribed()) System.out.println(tab + "Not Subscribed"); if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { if (folder.hasNewMessages()) System.out.println(tab + "Has New Messages"); System.out.println(tab + "Total Messages: " + folder.getMessageCount()); System.out.println(tab + "New Messages: " + folder.getNewMessageCount()); System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount()); }/* www. java2 s .co m*/ if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) System.out.println(tab + "Is Directory"); /* * Demonstrate use of IMAP folder attributes * returned by the IMAP LIST response. */ if (folder instanceof IMAPFolder) { IMAPFolder f = (IMAPFolder) folder; String[] attrs = f.getAttributes(); if (attrs != null && attrs.length > 0) { System.out.println(tab + "IMAP Attributes:"); for (int i = 0; i < attrs.length; i++) System.out.println(tab + " " + attrs[i]); } } } System.out.println(); if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { if (recurse) { Folder[] f = folder.list(); for (int i = 0; i < f.length; i++) dumpFolder(f[i], recurse, tab + " "); } } }
From source file:MainClass.java
static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception { System.out.println(tab + "Name: " + folder.getName()); System.out.println(tab + "Full Name: " + folder.getFullName()); System.out.println(tab + "URL: " + folder.getURLName()); if (verbose) { if (!folder.isSubscribed()) System.out.println(tab + "Not Subscribed"); if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { if (folder.hasNewMessages()) System.out.println(tab + "Has New Messages"); System.out.println(tab + "Total Messages: " + folder.getMessageCount()); System.out.println(tab + "New Messages: " + folder.getNewMessageCount()); System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount()); }//ww w .j a v a 2 s . c o m if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) System.out.println(tab + "Is Directory"); /* * Demonstrate use of IMAP folder attributes returned by the IMAP LIST * response. */ if (folder instanceof IMAPFolder) { IMAPFolder f = (IMAPFolder) folder; String[] attrs = f.getAttributes(); if (attrs != null && attrs.length > 0) { System.out.println(tab + "IMAP Attributes:"); for (int i = 0; i < attrs.length; i++) System.out.println(tab + " " + attrs[i]); } } } System.out.println(); if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { if (recurse) { Folder[] f = folder.list(); for (int i = 0; i < f.length; i++) dumpFolder(f[i], recurse, tab + " "); } } }
From source file:org.jasig.portlet.emailpreview.controller.AjaxUpdateInboxFolderController.java
@ResourceMapping("inboxFolder") public ModelAndView inboxFolder(ResourceRequest req, ResourceResponse res) throws MessagingException { IEmailAccountService accountDao = serviceBroker.getEmailAccountService(req); PortletPreferences prefs = req.getPreferences(); String selectedFolder = prefs.getValue(EmailAccountSummaryController.INBOX_NAME_PREFERENCE, INBOX_DEFAULT_VALUE_PREF);// w w w .ja v a2 s.c o m String authenticationServiceKey = prefs.getValue(AUTH_SERVICE_PREFERENCE, AUTH_SERVICE_DEFAULT_VALUE_PREFERENCE); Map<String, String> jsonData = new Hashtable<String, String>(); if (AUTH_SERVICE_TEST_PREFERENCE.equals(authenticationServiceKey)) { jsonData.put("INBOX", "INBOX"); //For demo : must have the same name that the json files in src/main/resources jsonData.put("demoTest", "demoTest"); jsonData.put("Important", "Important"); for (Map.Entry<String, String> entry : jsonData.entrySet()) { if (entry.getValue().equals(selectedFolder)) { jsonData.put(SELECTED_OPTION, entry.getValue()); break; } } } else { for (Folder folderName : accountDao.getAllUserInboxFolders(req)) { if ((folderName.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) { String unreadMsgCount = ""; if (folderName.getUnreadMessageCount() != 0 && (!selectedFolder.equals(folderName.toString()))) { unreadMsgCount = " (".concat(String.valueOf(folderName.getUnreadMessageCount())).concat(")") .concat(UNREAD_MSG_FLAG); } jsonData.put(folderName.toString().concat(unreadMsgCount), folderName.toString()); if (selectedFolder.equals(folderName.toString())) { jsonData.put(SELECTED_OPTION, folderName.toString()); } } } } return new ModelAndView("json", jsonData); }
From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
public Message[] getPOPMessages(Folder folder, int retrievemails) throws Exception { // Get messages .. try {/*from w ww .jav a2s . c om*/ int unreadMsgs = folder.getUnreadMessageCount(); Message msgsAll[] = folder.getMessages(); int msgCount = msgsAll.length; if (retrievemails == 1) { Message msgsUnread[] = folder.getMessages(msgCount - unreadMsgs + 1, msgCount); return (msgsUnread); } else { return (msgsAll); } } catch (Exception e) { return null; } }
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;/* ww w .jav a2 s . c om*/ 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:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
@SuppressWarnings({ "unchecked" }) public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false);/*from w w w. j a v a 2 s. c om*/ result.setNrErrors(1); //Get system properties Properties prop = new Properties(); prop.setProperty("mail.pop3s.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //Create session object Session sess = Session.getDefaultInstance(prop, null); sess.setDebug(true); FileObject fileObject = null; Store st = null; Folder f = null; try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); String realOutputFolder = getRealOutputDirectory(); fileObject = KettleVFS.getFileObject(realOutputFolder); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists.Label", realOutputFolder)); //$NON-NLS-1$ } else { if (fileObject.getType() == FileType.FOLDER) { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); //$NON-NLS-1$ // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.fallback", "false"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.port", getRealSSLPort()); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); //$NON-NLS-1$ URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); //$NON-NLS-1$ //$NON-NLS-2$ st = new POP3SSLStore(sess, url); st.connect(); } if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //$NON-NLS-1$ //Open the INBOX FOLDER // For POP3, the only folder available is the INBOX. f = st.getFolder("INBOX"); //$NON-NLS-1$ if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); //$NON-NLS-1$ } else { // Open folder if (delete) f.open(Folder.READ_WRITE); else f.open(Folder.READ_ONLY); Message messageList[] = f.getMessages(); if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder.Label", f.getName(), //$NON-NLS-1$ String.valueOf(messageList.length))); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder.Label", //$NON-NLS-1$ f.getName(), String.valueOf(f.getUnreadMessageCount()))); } // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List<File> current_file_POP = new ArrayList<File>(); List<String> current_filepath_POP = new ArrayList<String>(); int nb_email_POP = 1; String startpattern = "name"; //$NON-NLS-1$ if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label", //$NON-NLS-1$ msg_list[i].getFrom()[0].toString())); log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.EmailSubject.Label", msg_list[i].getSubject())); //$NON-NLS-1$ } String localfilename_message = startpattern + "_" //$NON-NLS-1$ + StringUtil.getFormattedDateTimeNow(true) + "_" + (i + 1) + ".mail"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDetailed()) log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.LocalFilename.Label", localfilename_message)); //$NON-NLS-1$ File filename_message = new File(realOutputFolder, localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration<Header> enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") //$NON-NLS-1$ .append(header_POP.getValue()).append("\r\n").toString().getBytes()); //$NON-NLS-1$ } os_filename.write("\r\n".getBytes()); //$NON-NLS-1$ InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); // Check attachments Object content = msg_POP.getContent(); if (content instanceof Multipart) { handleMultipart(realOutputFolder, (Multipart) content); } // Check if mail has to be deleted if (delete) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); //$NON-NLS-1$ msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } result.setNrErrors(0); result.setResult(true); } } else { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.Error.NotAFolder", realOutputFolder)); } } } catch (NoSuchProviderException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.ProviderException", e.getMessage())); //$NON-NLS-1$ } catch (MessagingException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.MessagingException", e.getMessage())); //$NON-NLS-1$ } catch (Exception e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.GeneralException", e.getMessage())); //$NON-NLS-1$ } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } //close the folder, passing in a true value to expunge the deleted message try { if (f != null) f.close(true); if (st != null) st.close(); } catch (Exception e) { log.logError(toString(), e.getMessage()); } // free memory f = null; st = null; sess = null; } return result; }
From source file:org.apache.hupa.server.handler.FetchFoldersHandler.java
/** * Create a new IMAPFolder from the given Folder * //from w w w .jav a2s . c om * @param folder Current folder * @return imapFolder Created IMAPFolder * @throws ActionException If an error occurs * @throws MessagingException If an error occurs */ private IMAPFolder createIMAPFolder(Folder folder) throws ActionException { String fullName = folder.getFullName(); String delimiter; IMAPFolder iFolder = null; try { logger.debug("Creating folder: " + fullName + " for user: " + getUser()); delimiter = String.valueOf(folder.getSeparator()); iFolder = new IMAPFolder(fullName); iFolder.setDelimiter(delimiter); if ("[Gmail]".equals(folder.getFullName())) return iFolder; iFolder.setMessageCount(folder.getMessageCount()); iFolder.setSubscribed(folder.isSubscribed()); iFolder.setUnseenMessageCount(folder.getUnreadMessageCount()); } catch (MessagingException e) { logger.error("Unable to construct folder " + folder.getFullName(), e); } return iFolder; }
From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java
@Override public ArrayList<FolderItem> getFolderTree() throws MessagingException { getLogger().debug("getFolderTree"); assert (getMailSource() != null); ArrayList<FolderItem> folderItems = new ArrayList<FolderItem>(); Store store = getJavamailStore();/* w w w .j a va 2s. co m*/ store.connect(); Folder defaultFolder = store.getDefaultFolder(); FolderItem item = new FolderItem(); item.setIndex(0); item.setLevel(0); item.setName(defaultFolder.getName()); item.setFullName(defaultFolder.getFullName()); if ((defaultFolder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) { item.setMessageCount(defaultFolder.getMessageCount()); item.setUnreadMessageCount(defaultFolder.getUnreadMessageCount()); item.setNewMessageCount(defaultFolder.getNewMessageCount()); } Folder[] folders = defaultFolder.list("*"); if (ArrayUtils.isEmpty(folders)) { folders = defaultFolder.list(); } getLogger().debug("Found folders {}", ArrayUtils.toString(folders)); int index = 1; int level = 1; // TODO not really managing folders here, just listing them for (Folder folder : folders) { item = new FolderItem(); item.setIndex(index); item.setLevel(level); item.setName(folder.getName()); item.setFullName(folder.getFullName()); if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) { item.setMessageCount(folder.getMessageCount()); item.setUnreadMessageCount(folder.getUnreadMessageCount()); item.setNewMessageCount(folder.getNewMessageCount()); folderItems.add(item); } } store.close(); return folderItems; }
From source file:org.xwiki.contrib.mail.internal.DefaultMailReader.java
@Override public ArrayList<FolderItem> getFolderTree() throws MessagingException { assert (getMailSource() != null); assert (getMailSource().getHostname() != null); ArrayList<FolderItem> folderItems = new ArrayList<FolderItem>(); store = null;// w w w.ja v a2 s. co m boolean isGmail = getMailSource().getHostname() != null && getMailSource().getHostname().endsWith(".gmail.com"); logger.info("Listing folders for " + getMailSource().getHostname()); this.session = createSession(getMailSource().getProtocol(), getMailSource().getAdditionalProperties(), isGmail, getMailSource().isAutoTrustSSLCertificates()); // Get a Store object store = session.getStore(); // Connect to the mail account store.connect(getMailSource().getHostname(), getMailSource().getPort(), getMailSource().getUsername(), getMailSource().getPassword()); Folder defaultFolder = store.getDefaultFolder(); FolderItem item = new FolderItem(); item.setIndex(0); item.setLevel(0); item.setName(defaultFolder.getName()); item.setFullName(defaultFolder.getFullName()); if ((defaultFolder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) { item.setMessageCount(defaultFolder.getMessageCount()); item.setUnreadMessageCount(defaultFolder.getUnreadMessageCount()); item.setNewMessageCount(defaultFolder.getNewMessageCount()); } Folder[] folders = defaultFolder.list("*"); int index = 1; int level = 1; // TODO not really managing folders here, just listing them for (Folder folder : folders) { item = new FolderItem(); item.setIndex(index); item.setLevel(level); item.setName(folder.getName()); item.setFullName(folder.getFullName()); if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) { item.setMessageCount(folder.getMessageCount()); item.setUnreadMessageCount(folder.getUnreadMessageCount()); item.setNewMessageCount(folder.getNewMessageCount()); folderItems.add(item); } } store.close(); return folderItems; }