List of usage examples for javax.mail Folder getURLName
public URLName getURLName() throws MessagingException
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()); }//from w w w.j a va 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: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()); }//w w w.ja v a2 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:de.saly.elasticsearch.importer.imap.maildestination.ElasticsearchMailDestination.java
@Override public void clearDataForFolder(final Folder folder) throws IOException, MessagingException { logger.info("Delete locally all messages for folder {} in {}/{}", folder.getURLName().toString(), index, type);/*from www . ja v a2 s. co m*/ createIndexIfNotExists(); client.admin().indices().refresh(new RefreshRequest()).actionGet(); DeleteByQuery.deleteByQuery(client, index, new String[] { type }, QueryBuilders.termQuery("folderUri", folder.getURLName().toString())); }
From source file:de.saly.elasticsearch.importer.imap.maildestination.ElasticsearchMailDestination.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override/*from ww w . j a v a 2 s . c o m*/ public Set getCurrentlyStoredMessageUids(final Folder folder) throws IOException, MessagingException { createIndexIfNotExists(); client.admin().indices().refresh(new RefreshRequest()).actionGet(); final Set uids = new HashSet(); final TermQueryBuilder b = QueryBuilders.termQuery("folderUri", folder.getURLName().toString()); logger.debug("Term query: " + b.buildAsBytes().toUtf8()); SearchResponse scrollResp = client.prepareSearch().setIndices(index).setTypes(type) .setSearchType(SearchType.SCAN).setQuery(b).setScroll(new TimeValue(1000)).setSize(1000).execute() .actionGet(); while (true) { scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(1000)) .execute().actionGet(); boolean hitsRead = false; for (final SearchHit hit : scrollResp.getHits()) { hitsRead = true; if (folder instanceof IMAPFolder) { uids.add(Long.parseLong(hit.getId().split("::")[0])); } else { uids.add(hit.getId().split("::")[0]); } logger.debug("Local: " + hit.getId()); } if (!hitsRead) { break; } } logger.debug("Currently locally stored messages for folder {}: {}", folder.getURLName(), uids.size()); return uids; }
From source file:de.saly.elasticsearch.importer.imap.maildestination.ElasticsearchMailDestination.java
@SuppressWarnings("rawtypes") @Override/*from w w w . j a va 2 s . c o m*/ public void onMessageDeletes(final Set msgs, final Folder folder) throws IOException, MessagingException { if (msgs.size() == 0) { return; } createIndexIfNotExists(); client.admin().indices().refresh(new RefreshRequest()).actionGet(); logger.info( "Will delete " + msgs.size() + " messages locally for folder " + folder.getURLName().toString()); final BoolQueryBuilder query = new BoolQueryBuilder(); if (folder instanceof POP3Folder) { query.must(QueryBuilders.termsQuery("popId", msgs)); } else { query.must(QueryBuilders.termsQuery("uid", msgs)); } query.must(QueryBuilders.termQuery("folderUri", folder.getURLName().toString())); DeleteByQuery.deleteByQuery(client, index, new String[] { type }, query); }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Move {@link GmailMessage} to a given destination folder. * * @param destFolder the destination {@link Folder} name.See {@see ImapGmailLabel} * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()} * @throws GmailException if it fails to move {@link GmailMessage} to the * destination folder//from w w w . j a v a 2 s .c om */ public void moveTo(ImapGmailLabel destFolder, int messageNumber) { if (messageNumber <= 0) { throw new GmailException("ImapGmailClient invalid GmailMessage number"); } Folder fromFolder = null; Folder toFolder = null; try { final Store store = openGmailStore(); fromFolder = getFolder(this.srcFolder, store); fromFolder.open(Folder.READ_WRITE); Message message = fromFolder.getMessage(messageNumber); if (message != null) { toFolder = getFolder(destFolder.getName(), store); if (fromFolder.getURLName().equals(toFolder.getURLName())) { throw new GmailException("ImapGmailClient cannot move " + "GmailMessage within same folder " + "(from " + fromFolder.getFullName() + " to " + toFolder.getFullName() + ")"); } // copy from source folder to destination folder fromFolder.copyMessages(new Message[] { message }, toFolder); // move the copied message to trash folder moveToTrash(new GmailMessage[] { new JavaMailGmailMessage(message) }); } } catch (GmailException ge) { throw ge; } catch (Exception e) { throw new GmailException( "ImapGmailClient failed moving" + " GmailMessage from " + fromFolder.getFullName(), e); } finally { closeFolder(fromFolder); } }
From source file:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java
@SuppressWarnings({ "rawtypes", "unchecked" }) protected void fetch(final Folder folder) throws MessagingException, IOException { if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) { logger.warn("Folder {} cannot hold messages", folder.getFullName()); return;//from ww w .j a va 2s . c o m } final int messageCount = folder.getMessageCount(); final UIDFolder uidfolder = (UIDFolder) folder; final long servervalidity = uidfolder.getUIDValidity(); final RiverState riverState = stateManager.getRiverState(folder); final Long localvalidity = riverState.getUidValidity(); logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount); logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity); if (localvalidity == null || localvalidity.longValue() != servervalidity) { logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity); if (localvalidity != null) { mailDestination.clearDataForFolder(folder.getFullName()); } final ProcessResult result = process(messageCount, 1, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { if (messageCount == 0) { logger.debug("Folder {} is empty", folder.getFullName()); } else { if (withFlagSync) { // detect flag change final Message[] flagMessages = folder.getMessages(); folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID); for (final Message message : flagMessages) { try { final long uid = ((UIDFolder) message.getFolder()).getUID(message); final String id = uid + "::" + message.getFolder().getURLName(); final int storedHashcode = mailDestination.getFlaghashcode(id); if (storedHashcode == -1) { // New mail which is not indexed yet continue; } final int flagHashcode = message.getFlags().hashCode(); if (flagHashcode != storedHashcode) { // flags change for this message, must update mailDestination.onMessage(message); if (logger.isDebugEnabled()) { logger.debug("Update " + id + " because of flag change"); } } } catch (final Exception e) { logger.error("Error detecting flagchanges for message " + ((MimeMessage) message).getMessageID(), e); stateManager.onError("Error detecting flagchanges", message, e); } } } final long highestUID = riverState.getLastUid(); // this uid is // already // processed logger.debug("highestUID: {}", highestUID); final Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID); // msgnew.size is always >= 1 if (highestUID > 0 && uidfolder.getUID(msgsnew[0]) <= highestUID) { // msgsnew = (Message[]) ArrayUtils.remove(msgsnew, 0); } if (msgsnew.length > 0) { logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName()); final int start = msgsnew[0].getMessageNumber(); final ProcessResult result = process(messageCount, start, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { logger.debug("no new messages"); } } // check for expunged/deleted messages final Set<Long> serverMailSet = new HashSet<Long>(); final long oldmailUid = riverState.getLastUid(); logger.debug("oldmailuid {}", oldmailUid); final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid); folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID); for (final Message m : msgsold) { try { final long uid = uidfolder.getUID(m); serverMailSet.add(uid); } catch (final Exception e) { stateManager.onError("Unable to handle old message ", m, e); logger.error("Unable to handle old message due to {}", e, e.toString()); IMAPUtils.open(folder); } } final Set localMailSet = new HashSet( mailDestination.getCurrentlyStoredMessageUids(folder.getFullName(), false)); logger.debug("Check now " + localMailSet.size() + " server mails for expunge"); localMailSet.removeAll(serverMailSet); // localMailSet has now the ones that are not on server logger.info( localMailSet.size() + " messages were locally deleted, because they are expunged on server."); mailDestination.onMessageDeletes(localMailSet, folder.getFullName(), false); } }
From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java
@SuppressWarnings({ "rawtypes", "unchecked" }) protected void fetch(final Folder folder) throws MessagingException, IOException { if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) { logger.warn("Folder {} cannot hold messages", folder.getFullName()); return;//w w w .j a v a2 s . c om } final int messageCount = folder.getMessageCount(); final UIDFolder uidfolder = (UIDFolder) folder; final long servervalidity = uidfolder.getUIDValidity(); final State riverState = stateManager.getRiverState(folder); final Long localvalidity = riverState.getUidValidity(); logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount); logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity); if (localvalidity == null || localvalidity.longValue() != servervalidity) { logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity); if (localvalidity != null) { mailDestination.clearDataForFolder(folder); } final ProcessResult result = process(messageCount, 1, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { if (messageCount == 0) { logger.debug("Folder {} is empty", folder.getFullName()); } else { if (withFlagSync) { // detect flag change final Message[] flagMessages = folder.getMessages(); folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID); for (final Message message : flagMessages) { try { final long uid = ((UIDFolder) message.getFolder()).getUID(message); final String id = uid + "::" + message.getFolder().getURLName(); final int storedHashcode = mailDestination.getFlaghashcode(id); if (storedHashcode == -1) { // New mail which is not indexed yet continue; } final int flagHashcode = message.getFlags().hashCode(); if (flagHashcode != storedHashcode) { // flags change for this message, must update mailDestination.onMessage(message); if (logger.isDebugEnabled()) { logger.debug("Update " + id + " because of flag change"); } } } catch (final Exception e) { logger.error("Error detecting flagchanges for message " + ((MimeMessage) message).getMessageID(), e); stateManager.onError("Error detecting flagchanges", message, e); } } } long highestUID = riverState.getLastUid(); // this uid is // already // processed logger.debug("highestUID: {}", highestUID); if (highestUID < 1) { logger.error("highestUID: {} not valid, set it to 1", highestUID); highestUID = 1; } Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID); if (msgsnew.length > 0) { System.out.println("lastuid: " + uidfolder.getUID(msgsnew[msgsnew.length - 1])); // msgnew.size is always >= 1 if (highestUID > 1 && uidfolder.getUID(msgsnew[msgsnew.length - 1]) <= highestUID) { msgsnew = (Message[]) ArrayUtils.remove(msgsnew, msgsnew.length - 1); } if (msgsnew.length > 0) { logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName()); final int start = msgsnew[0].getMessageNumber(); final ProcessResult result = process(messageCount, start, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { logger.debug("no new messages"); } } else { logger.debug("no new messages"); } } // check for expunged/deleted messages final Set<Long> serverMailSet = new HashSet<Long>(); final long oldmailUid = riverState.getLastUid(); logger.debug("oldmailuid {}", oldmailUid); final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid); folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID); for (final Message m : msgsold) { try { final long uid = uidfolder.getUID(m); serverMailSet.add(uid); } catch (final Exception e) { stateManager.onError("Unable to handle old message ", m, e); logger.error("Unable to handle old message due to {}", e, e.toString()); IMAPUtils.open(folder); } } if (deleteExpungedMessages) { final Set localMailSet = new HashSet(mailDestination.getCurrentlyStoredMessageUids(folder)); logger.debug("Check now " + localMailSet.size() + " server mails for expunge"); localMailSet.removeAll(serverMailSet); // localMailSet has now the ones that are not on server logger.info(localMailSet.size() + " messages were locally deleted, because they are expunged on server."); mailDestination.onMessageDeletes(localMailSet, folder); } } }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Moves given {@link GmailMessage}'s to {@link ImapGmailLabel.TRASH} folder. * * @param gmailMessages {@link GmailMessage} message(s) * @throws GmailException if unable to move {@link GmailMessage}'s to * the Trash Folder//www . ja v a 2 s. c o m */ public void moveToTrash(final GmailMessage[] gmailMessages) { if (gmailMessages == null || gmailMessages.length <= 0) { LOG.warn("ImapGmailClient requires GmailMessage(s) to move" + " to move messages to trash folder"); return; } Folder folder = null; try { final Store store = openGmailStore(); folder = getFolder(this.srcFolder, store); if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } List<Message> markedMsgList = new ArrayList<Message>(); for (GmailMessage gmailMessage : gmailMessages) { // get only messages that match to the specified message number Message message = folder.getMessage(gmailMessage.getMessageNumber()); message.setFlag(Flags.Flag.SEEN, true); // mark message as delete message.setFlag(Flags.Flag.DELETED, true); markedMsgList.add(message); } Folder trash = getFolder(ImapGmailLabel.TRASH.getName(), store); if (folder.getURLName().equals(trash.getURLName())) { LOG.warn("ImapGmailClient trying to move GmailMessage(s) within" + " same folder(ImapGmailLabel.TRASH.getName())"); } // move the marked messages to trash folder if (!markedMsgList.isEmpty()) { folder.copyMessages(markedMsgList.toArray(new Message[0]), trash); } } catch (Exception e) { throw new GmailException("ImapGmailClient failed moving GmailMessage(s)" + " to trash folder: " + e); } finally { closeFolder(folder); } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * This method tries to generate a unique folder identifier for the given folder. * This method generates an MD5 sum over the complete folder URL, if possible. * @see getFolderTree/*from w w w.j av a2 s . c o m*/ * @see net.wastl.webmail.misc.MD5 */ protected String generateFolderHash(Folder folder) { String id = Integer.toHexString(folder.hashCode()); // If possible, use the MD5-Sum for the folder ID because it is persistant over sessions try { MD5 md5 = new MD5(folder.getURLName()); id = md5.asHex(); } catch (MessagingException ex) { } return id; }