List of usage examples for javax.mail UIDFolder getUID
public long getUID(Message message) throws MessagingException;
From source file:uidmsgshow.java
public static void main(String argv[]) { long uid = -1; int optind;/*from w w w. ja v a 2 s . c o m*/ for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-f")) { mbox = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println( "Usage: uidmsgshow [-L url] [-T protocol] [-H host] [-U user] [-P password] [-f mailbox] [uid] [-v]"); System.exit(1); } else { break; } } try { if (optind < argv.length) uid = Long.parseLong(argv[optind]); // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); // session.setDebug(true); // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Open the Folder Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("No default folder"); System.exit(1); } folder = folder.getFolder(mbox); if (!folder.exists()) { System.out.println(mbox + " does not exist"); System.exit(1); } if (!(folder instanceof UIDFolder)) { System.out.println("This Provider or this folder does not support UIDs"); System.exit(1); } UIDFolder ufolder = (UIDFolder) folder; folder.open(Folder.READ_WRITE); int totalMessages = folder.getMessageCount(); if (totalMessages == 0) { System.out.println("Empty folder"); folder.close(false); store.close(); System.exit(1); } if (verbose) { int newMessages = folder.getNewMessageCount(); System.out.println("Total messages = " + totalMessages); System.out.println("New messages = " + newMessages); System.out.println("-------------------------------"); } if (uid == -1) { // Attributes & Flags for ALL messages .. Message[] msgs = ufolder.getMessagesByUID(1, UIDFolder.LASTUID); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { System.out.println("--------------------------"); System.out.println("MESSAGE UID #" + ufolder.getUID(msgs[i]) + ":"); dumpEnvelope(msgs[i]); // dumpPart(msgs[i]); } } else { System.out.println("Getting message UID: " + uid); Message m = ufolder.getMessageByUID(uid); if (m != null) dumpPart(m); else System.out.println("This Message does not exist on this folder"); } folder.close(false); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); } System.exit(1); }
From source file:de.bht.fpa.mail.s000000.common.mail.imapsync.MessageConverter.java
private static long convertId(UIDFolder uidFolder, javax.mail.Message javaMailMessage) throws MessagingException { return uidFolder.getUID(javaMailMessage); }
From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java
protected void parseMessage(MimeMessage msg, UIDFolder folder) { try {/*from ww w .j av a 2s. c om*/ if (uid == -1) { uid = folder.getUID(msg); } if (id == null) { id = msg.getMessageID(); } if (inReplyTo == null) { String[] headers = msg.getHeader(IN_REPLY_TO); if (headers != null) { if (headers.length == 1) inReplyTo = headers[0]; else if (headers.length > 1) throw new EmailMessageException(ERR_EXTRACTING_IN_REPLY_TO, "Not more than one " + IN_REPLY_TO + " header expected"); } } } catch (MessagingException e) { throw new EmailMessageException(ERR_EXTRACTING_ATTRS, e.getMessage()); } }
From source file:com.liferay.mail.imap.IMAPAccessor.java
protected long getUID(Folder jxFolder, Message jxMessage) throws MessagingException { UIDFolder uidFolder = (UIDFolder) jxFolder; return uidFolder.getUID(jxMessage); }
From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java
private ProcessResult processMessageSlice(final int start, final int end, final String folderName) throws Exception { logger.debug("processMessageSlice() started with " + start + "/" + end + "/" + folderName); final long startTime = System.currentTimeMillis(); final Store store = Session.getInstance(props).getStore(); store.connect(user, password);//www . j a v a 2 s .c o m final Folder folder = store.getFolder(folderName); final UIDFolder uidfolder = (UIDFolder) folder; IMAPUtils.open(folder); try { final Message[] msgs = folder.getMessages(start, end); folder.fetch(msgs, IMAPUtils.FETCH_PROFILE_HEAD); logger.debug("folder fetch done"); long highestUid = 0; int processedCount = 0; for (final Message m : msgs) { try { IMAPUtils.open(folder); final long uid = uidfolder.getUID(m); mailDestination.onMessage(m); highestUid = Math.max(highestUid, uid); processedCount++; if (Thread.currentThread().isInterrupted()) { break; } } catch (final Exception e) { stateManager.onError("Unable to make indexable message", m, e); logger.error("Unable to make indexable message due to {}", e, e.toString()); IMAPUtils.open(folder); } } final long endTime = System.currentTimeMillis() + 1; final ProcessResult pr = new ProcessResult(highestUid, processedCount, endTime - startTime); logger.debug("processMessageSlice() ended with " + pr); return pr; } finally { IMAPUtils.close(folder); IMAPUtils.close(store); } }
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;/* w w 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 av a2 s . c o m } 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); } } }