List of usage examples for javax.mail Store getDefaultFolder
public abstract Folder getDefaultFolder() throws MessagingException;
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
@Override public List<Folder> getAllUserInboxFolders(MailStoreConfiguration config) { Authenticator auth = credentialsProvider.getAuthenticator(); Store store = null; try {/*from ww w.java 2 s . c o m*/ Session session = openMailSession(config, auth); // Assertions. if (session == null) { String msg = "Argument 'session' cannot be null"; throw new IllegalArgumentException(msg); } store = session.getStore(); store.connect(); if (log.isDebugEnabled()) { log.debug("Mail store connection established to get all user inbox folders"); } // Retrieve user's inbox folder return Arrays.asList(store.getDefaultFolder().list("*")); } catch (Exception e) { log.error("Can't get all user Inbox folders"); return null; } finally { if (store != null) { try { store.close(); } catch (Exception e) { log.warn("Can't close correctly javamail store connection"); } } } }
From source file:org.zilverline.core.IMAPCollection.java
/** * Sets existsOnDisk based on whether the collection (contentDir) actually (now) sits on disk. * //from ww w. j av a2 s .co m * @todo the whole existsOnDisk construction is a little funny, refactor some time */ protected void setExistsOnDisk() { existsOnDisk = false; Store store = null; try { // try to connect to server and find folder log.debug("Connecting to IMAP server: " + host); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); store = session.getStore("imap"); log.debug("Connecting to " + host + " as " + user); store.connect(host, user, password); log.debug("Connected"); // start at the proper folder Folder topFolder = null; if (StringUtils.hasText(folder)) { topFolder = store.getFolder(folder); } else { topFolder = store.getDefaultFolder(); } existsOnDisk = (topFolder != null); } catch (NoSuchProviderException e) { log.warn("Can't connect to " + host, e); } catch (MessagingException e) { log.warn("Error while accessing IMAP server " + host, e); } finally { if (store != null) { try { store.close(); } catch (MessagingException e1) { log.error("Error closing IMAP server " + host, e1); } } } }
From source file:com.zotoh.maedr.device.PopIO.java
private boolean conn() { if (_pop == null || !_pop.isConnected()) try {// ww w . j ava 2s .co m Session session = Session.getInstance(new Properties(), null); Provider[] ps = session.getProviders(); Provider sun = null; Store st = null; Folder f = null; String uid = isEmpty(_user) ? null : _user; String pwd = isEmpty(_pwd) ? null : _pwd; String key = ST_POP3, sn = POP3; closePOP(); if (_ssl) { key = ST_POP3S; sn = POP3S; } for (int i = 0; i < ps.length; ++i) { if (key.equals(ps[i].getClassName())) { sun = ps[i]; break; } } if (!isEmpty(_storeImpl)) { // this should never happen , only in testing sun = new Provider(Provider.Type.STORE, "pop3", _storeImpl, "test", "1.0.0"); sn = POP3; } session.setProvider(sun); st = session.getStore(sn); if (st != null) { st.connect(_host, _port, uid, pwd); f = st.getDefaultFolder(); } if (f != null) { f = f.getFolder("INBOX"); } if (f == null || !f.exists()) { throw new Exception("POP3: Cannot find inbox"); } _pop = st; _fd = f; } catch (Exception e) { tlog().warn("", e); closePOP(); } return _pop != null && _pop.isConnected(); }
From source file:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java
protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException { logger.debug("fetch() - pattern: {}, folderName: {}", pattern, folderName); final Store store = Session.getInstance(props).getStore(); store.connect(user, password);/*from www. j ava 2s . c o m*/ try { for (final String fol : mailDestination.getFolderNames()) { if (store.getFolder(fol).exists()) { logger.debug("{} exists", fol); } else { logger.info( "Folder {} does not exist on the server, will remove it (and its content) also locally", fol); final RiverState riverState = stateManager.getRiverState(store.getFolder(fol)); riverState.setExists(false); stateManager.setRiverState(riverState); try { mailDestination.clearDataForFolder(fol); } catch (final Exception e) { stateManager.onError("Unable to clean data for stale folder", store.getFolder(fol), e); } } } } catch (final IndexMissingException ime) { logger.debug(ime.toString()); } catch (final Exception e) { logger.error("Error checking for stale folders", e); } final boolean isRoot = StringUtils.isEmpty(folderName); final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName); try { if (!folder.exists()) { logger.error("Folder {} does not exist on the server", folder.getFullName()); return; } logger.debug("folderName: {} is root: {}", folderName, isRoot); /*if (logger.isDebugEnabled() && store instanceof IMAPStore) { IMAPStore imapStore = (IMAPStore) store; logger.debug("IMAP server capability info"); logger.debug("IMAP4rev1: " + imapStore.hasCapability("IMAP4rev1")); logger.debug("IDLE: " + imapStore.hasCapability("IDLE")); logger.debug("ID: " + imapStore.hasCapability("ID")); logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS")); logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN")); logger.debug("NAMESPACE: " + imapStore.hasCapability("NAMESPACE")); logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY")); logger.debug("CONDSTORE: " + imapStore.hasCapability("CONDSTORE")); logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC")); logger.debug("STATUS: " + imapStore.hasCapability("STATUS")); }*/ if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) { logger.info(folder.getFullName() + " does not match pattern " + pattern.toString()); return; } IMAPUtils.open(folder); recurseFolders(folder, pattern); } finally { IMAPUtils.close(folder); IMAPUtils.close(store); } }
From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java
protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException { logger.debug("fetch() - pattern: {}, folderName: {}, user: {}", pattern, folderName, user); final Store store = Session.getInstance(props).getStore(); store.connect(user, password);/* www.java 2s . com*/ if (deleteExpungedMessages) { try { for (final String fol : mailDestination.getFolderNames()) { if (store.getFolder(fol).exists()) { logger.debug("{} exists for {}", fol, user); } else { logger.info( "Folder {} does not exist for {} on the server, will remove it (and its content) also locally", user, fol); final State riverState = stateManager.getRiverState(store.getFolder(fol)); riverState.setExists(false); stateManager.setRiverState(riverState); try { mailDestination.clearDataForFolder(store.getFolder(fol)); } catch (final Exception e) { stateManager.onError("Unable to clean data for stale folder for " + user, store.getFolder(fol), e); } } } } /*catch (final IndexMissingException ime) { logger.debug(ime.toString()); //TODO 2.0 check } */ catch (final Exception e) { logger.error("Error checking for stale folders", e); } } final boolean isRoot = StringUtils.isEmpty(folderName); final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName); try { if (!folder.exists()) { logger.error("Folder {} does not exist on the server", folder.getFullName()); return; } logger.debug("folderName: {} is root: {}", folderName, isRoot); /*if (logger.isDebugEnabled() && store instanceof IMAPStore) { IMAPStore imapStore = (IMAPStore) store; logger.debug("IMAP server capability info"); logger.debug("IMAP4rev1: " + imapStore.hasCapability("IMAP4rev1")); logger.debug("IDLE: " + imapStore.hasCapability("IDLE")); logger.debug("ID: " + imapStore.hasCapability("ID")); logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS")); logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN")); logger.debug("NAMESPACE: " + imapStore.hasCapability("NAMESPACE")); logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY")); logger.debug("CONDSTORE: " + imapStore.hasCapability("CONDSTORE")); logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC")); logger.debug("STATUS: " + imapStore.hasCapability("STATUS")); }*/ if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) { logger.debug(folder.getFullName() + " does not match pattern " + pattern.toString()); return; } IMAPUtils.open(folder); recurseFolders(folder, pattern); } finally { IMAPUtils.close(folder); IMAPUtils.close(store); } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** Connect to mailhost "name"//from w w w . ja v a 2s . co m */ public Folder connect(String name) throws MessagingException { MailHostData m = user.getMailHost(name); URLName url = new URLName(m.getHostURL()); Store st = connectStore(url.getHost(), url.getProtocol(), m.getLogin(), m.getPassword()); Folder f = st.getDefaultFolder(); connections.put(name, f); log.info("Mail: Default folder '" + f.getFullName() + "' retrieved from store " + st + '.'); return f; }
From source file:org.zilverline.core.IMAPCollection.java
/** * Index the given Collection./*from w w w .java2s . c o m*/ * * @param fullIndex indicates whether a full or incremental index should be created * @throws IndexException if the Collections can not be indexed * @return true if succesfull */ private final boolean doIndex(boolean fullIndex) throws IndexException { IndexWriter writer = null; Store store = null; try { // record start time StopWatch watch = new StopWatch(); watch.start(); // make sure the index exists File indexDirectory = this.getIndexDirWithManagerDefaults(); // reindex if the index is not there or invalid boolean mustReindex = fullIndex; if (!this.isIndexValid()) { mustReindex = true; indexDirectory.mkdirs(); } // create an index(writer) writer = new IndexWriter(indexDirectory, this.createAnalyzer(), mustReindex); // see whether there are specific indexing settings in manager if (manager.getMergeFactor() != null) { writer.setMergeFactor(manager.getMergeFactor().intValue()); } if (manager.getMinMergeDocs() != null) { writer.setMaxBufferedDocs(manager.getMinMergeDocs().intValue()); } if (manager.getMaxMergeDocs() != null) { writer.setMaxMergeDocs(manager.getMaxMergeDocs().intValue()); } resetCache(fullIndex); // connect to IMAP log.debug("Connecting to IMAP server: " + host); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); store = session.getStore("imap"); log.debug("Connecting to " + host + " as " + user); store.connect(host, user, password); log.debug("Connected"); // start at the proper folder Folder topFolder = null; if (StringUtils.hasText(folder)) { topFolder = store.getFolder(folder); } else { topFolder = store.getDefaultFolder(); } indexFolder(writer, topFolder); // record end time and report duration of indexing watch.stop(); log.info("Indexed " + writer.docCount() + " documents in " + watch.elapsedTime()); return true; } catch (NoSuchProviderException e) { throw new IndexException("Can't connect to " + host, e); } catch (MessagingException e) { throw new IndexException("Error while accessing IMAP server " + host, e); } catch (IOException e) { throw new IndexException("Error indexing '" + this.getName() + "'. Possibly unable to remove old index", e); } catch (Exception e) { throw new IndexException("Error indexing '" + this.getName() + "'", e); } finally { if (writer != null) { try { writer.optimize(); log.debug("Optimizing index for " + name); writer.close(); log.debug("Closing index for " + name); } catch (IOException e1) { log.error("Error closing Index for " + name, e1); } } if (store != null) { try { store.close(); } catch (MessagingException e1) { log.error("Error closing IMAP server " + host, e1); } } init(); } }
From source file:com.sonicle.webtop.core.app.WebTopManager.java
private void createCyrusMailbox(String login, Store store) throws WTCyrusException { try {/*from w ww . j a va 2 s. co m*/ char sep = store.getDefaultFolder().getSeparator(); Folder c = store.getFolder("user" + sep + login); if (!c.exists()) c.create(Folder.HOLDS_FOLDERS); } catch (Exception exc) { throw new WTCyrusException(exc); } }
From source file:com.sonicle.webtop.core.app.WebTopManager.java
public void setCyrusAcl(String login, String acllogin, Store store) throws WTCyrusException { try {/*from ww w . j a v a2 s. c o m*/ char sep = store.getDefaultFolder().getSeparator(); Folder f = store.getFolder("user" + sep + login); IMAPFolder folder = (IMAPFolder) f; Rights r = new Rights("lrswipcda"); ACL a = new ACL(acllogin, r); folder.addACL(a); } catch (Exception exc) { throw new WTCyrusException(exc); } }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
/** * The main method of this job. Called by confluence every time the mail2news trigger * fires./*from w ww . j ava 2s.co m*/ * * @see com.atlassian.quartz.jobs.AbstractJob#doExecute(org.quartz.JobExecutionContext) */ public void doExecute(JobExecutionContext arg0) throws JobExecutionException { /* The mailstore object used to connect to the server */ Store store = null; try { this.log.info("Executing mail2news plugin."); /* check if we have all necessary components */ if (pageManager == null) { throw new Exception("Null PageManager instance."); } if (spaceManager == null) { throw new Exception("Null SpaceManager instance."); } if (configurationManager == null) { throw new Exception("Null ConfigurationManager instance."); } /* get the mail configuration from the manager */ MailConfiguration config = configurationManager.getMailConfiguration(); if (config == null) { throw new Exception("Null MailConfiguration instance."); } /* create the properties for the session */ Properties prop = new Properties(); /* get the protocol to use */ if (config.getProtocol() == null) { throw new Exception("Cannot get protocol."); } String protocol = config.getProtocol().toLowerCase().concat(config.getSecure() ? "s" : ""); /* assemble the property prefix for this protocol */ String propertyPrefix = "mail."; propertyPrefix = propertyPrefix.concat(protocol).concat("."); /* get the server port from the configuration and add it to the properties, * but only if it is actually set. If port = 0 this means we use the standard * port for the chosen protocol */ int port = config.getPort(); if (port != 0) { prop.setProperty(propertyPrefix.concat("port"), "" + port); } /* set connection timeout (10 seconds) */ prop.setProperty(propertyPrefix.concat("connectiontimeout"), "10000"); /* get the session for connecting to the mail server */ Session session = Session.getInstance(prop, null); /* get the mail store, using the desired protocol */ if (config.getSecure()) { store = session.getStore(protocol); } else { store = session.getStore(protocol); } /* get the host and credentials for the mail server from the configuration */ String host = config.getServer(); String username = config.getUsername(); String password = config.getPassword(); /* sanity check */ if (host == null || username == null || password == null) { throw new Exception("Incomplete mail configuration settings (at least one setting is null)."); } /* connect to the mailstore */ try { store.connect(host, username, password); } catch (AuthenticationFailedException afe) { throw new Exception("Authentication for mail store failed: " + afe.getMessage(), afe); } catch (MessagingException me) { throw new Exception("Connecting to mail store failed: " + me.getMessage(), me); } catch (IllegalStateException ise) { throw new Exception("Connecting to mail store failed, already connected: " + ise.getMessage(), ise); } catch (Exception e) { throw new Exception("Connecting to mail store failed, general exception: " + e.getMessage(), e); } /*** * Open the INBOX ***/ /* get the INBOX folder */ Folder folderInbox = store.getFolder("INBOX"); /* we need to open it READ_WRITE, because we want to move messages we already handled */ try { folderInbox.open(Folder.READ_WRITE); } catch (FolderNotFoundException fnfe) { throw new Exception("Could not find INBOX folder: " + fnfe.getMessage(), fnfe); } catch (Exception e) { throw new Exception("Could not open INBOX folder: " + e.getMessage(), e); } /* here we have to split, because IMAP will be handled differently from POP3 */ if (config.getProtocol().toLowerCase().equals("imap")) { /*** * Open the default folder, under which will be the processed * and the invalid folder. ***/ Folder folderDefault = null; try { folderDefault = store.getDefaultFolder(); } catch (MessagingException me) { throw new Exception("Could not get default folder: " + me.getMessage(), me); } /* sanity check */ try { if (!folderDefault.exists()) { throw new Exception( "Default folder does not exist. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author."); } } catch (MessagingException me) { throw new Exception("Could not test existence of the default folder: " + me.getMessage(), me); } /** * This is kind of a fallback mechanism. For some reasons it can happen that * the default folder has an empty name and exists() returns true, but when * trying to create a subfolder it generates an error message. * So what we do here is if the name of the default folder is empty, we * look for the "INBOX" folder, which has to exist and then create the * subfolders under this folder. */ if (folderDefault.getName().equals("")) { this.log.warn("Default folder has empty name. Looking for 'INBOX' folder as root folder."); folderDefault = store.getFolder("INBOX"); if (!folderDefault.exists()) { throw new Exception( "Could not find default folder and could not find 'INBOX' folder. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author."); } } /*** * Open the folder for processed messages ***/ /* get the folder where we store processed messages */ Folder folderProcessed = folderDefault.getFolder("Processed"); /* check if it exists */ if (!folderProcessed.exists()) { /* does not exist, create it */ try { if (!folderProcessed.create(Folder.HOLDS_MESSAGES)) { throw new Exception("Creating 'processed' folder failed."); } } catch (MessagingException me) { throw new Exception("Could not create 'processed' folder: " + me.getMessage(), me); } } /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */ try { folderProcessed.open(Folder.READ_WRITE); } catch (FolderNotFoundException fnfe) { throw new Exception("Could not find 'processed' folder: " + fnfe.getMessage(), fnfe); } catch (Exception e) { throw new Exception("Could not open 'processed' folder: " + e.getMessage(), e); } /*** * Open the folder for invalid messages ***/ /* get the folder where we store invalid messages */ Folder folderInvalid = folderDefault.getFolder("Invalid"); /* check if it exists */ if (!folderInvalid.exists()) { /* does not exist, create it */ try { if (!folderInvalid.create(Folder.HOLDS_MESSAGES)) { throw new Exception("Creating 'invalid' folder failed."); } } catch (MessagingException me) { throw new Exception("Could not create 'invalid' folder: " + me.getMessage(), me); } } /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */ try { folderInvalid.open(Folder.READ_WRITE); } catch (FolderNotFoundException fnfe) { throw new Exception("Could not find 'invalid' folder: " + fnfe.getMessage(), fnfe); } catch (Exception e) { throw new Exception("Could not open 'invalid' folder: " + e.getMessage(), e); } /*** * Get all new messages ***/ /* get all messages in the INBOX */ Message message[] = folderInbox.getMessages(); /* go through all messages and get the unseen ones (all should be unseen, * as the seen ones get moved to a different folder */ for (int i = 0; i < message.length; i++) { if (message[i].isSet(Flags.Flag.SEEN)) { /* this message has been seen, should not happen */ /* send email to the sender */ sendErrorMessage(message[i], "This message has already been flagged as seen before being handled and was thus ignored."); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } Space space = null; try { space = getSpaceFromAddress(message[i]); } catch (Exception e) { this.log.error("Could not get space from message: " + e.getMessage()); /* send email to the sender */ sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage()); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } /* initialise content and attachments */ blogEntryContent = null; attachments = new LinkedList(); attachmentsInputStreams = new LinkedList(); containsImage = false; /* get the content of this message */ try { Object content = message[i].getContent(); if (content instanceof Multipart) { handleMultipart((Multipart) content); } else { handlePart(message[i]); } } catch (Exception e) { this.log.error("Error while getting content of message: " + e.getMessage(), e); /* send email to the sender */ sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage()); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } try { createBlogPost(space, message[i]); } catch (MessagingException me) { this.log.error("Error while creating blog post: " + me.getMessage(), me); /* send email to sender */ sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage()); /* move this message to the invalid folder */ moveMessage(message[i], folderInbox, folderInvalid); /* skip this message */ continue; } /* move the message to the processed folder */ moveMessage(message[i], folderInbox, folderProcessed); } /* close the folders, expunging deleted messages in the process */ folderInbox.close(true); folderProcessed.close(true); folderInvalid.close(true); /* close the store */ store.close(); } else if (config.getProtocol().toLowerCase().equals("pop3")) { /* get all messages in this POP3 account */ Message message[] = folderInbox.getMessages(); /* go through all messages */ for (int i = 0; i < message.length; i++) { Space space = null; try { space = getSpaceFromAddress(message[i]); } catch (Exception e) { this.log.error("Could not get space from message: " + e.getMessage()); /* send email to the sender */ sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage()); /* delete this message */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ continue; } /* initialise content and attachments */ blogEntryContent = null; attachments = new LinkedList(); attachmentsInputStreams = new LinkedList(); containsImage = false; /* get the content of this message */ try { Object content = message[i].getContent(); if (content instanceof Multipart) { handleMultipart((Multipart) content); } else { handlePart(message[i]); } } catch (Exception e) { this.log.error("Error while getting content of message: " + e.getMessage(), e); /* send email to the sender */ sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage()); /* delete this message */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ continue; } try { createBlogPost(space, message[i]); } catch (MessagingException me) { this.log.error("Error while creating blog post: " + me.getMessage(), me); /* send email to the sender */ sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage()); /* delete this message */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ continue; } /* finished processing this message, delete it */ message[i].setFlag(Flags.Flag.DELETED, true); /* get the next message, this message will be deleted when * closing the folder */ } /* close the pop3 folder, deleting all messages flagged as DELETED */ folderInbox.close(true); /* close the mail store */ store.close(); } else { throw new Exception("Unknown protocol: " + config.getProtocol()); } } catch (Exception e) { /* catch any exception which was not handled so far */ this.log.error("Error while executing mail2news job: " + e.getMessage(), e); JobExecutionException jee = new JobExecutionException( "Error while executing mail2news job: " + e.getMessage(), e, false); throw jee; } finally { /* try to do some cleanup */ try { store.close(); } catch (Exception e) { } } }