List of usage examples for javax.mail Folder exists
public abstract boolean exists() throws MessagingException;
From source file:com.cws.esolutions.core.utils.EmailUtils.java
/** * Processes and sends an email message as generated by the requesting * application. This method is utilized with a JNDI datasource. * * @param dataSource - The email message * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise * @param authList - If authRequired is true, this must be populated with the auth info * @return List - The list of email messages in the mailstore * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing *//* ww w .j a va2 s . c om*/ public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException { final String methodName = EmailUtils.CNAME + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("dataSource: {}", dataSource); DEBUGGER.debug("authRequired: {}", authRequired); DEBUGGER.debug("authList: {}", authList); } Folder mailFolder = null; Session mailSession = null; Folder archiveFolder = null; List<EmailMessage> emailMessages = null; Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -24); final Long TIME_PERIOD = cal.getTimeInMillis(); final URLName URL_NAME = (authRequired) ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1)) : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, null, null); if (DEBUG) { DEBUGGER.debug("timePeriod: {}", TIME_PERIOD); DEBUGGER.debug("URL_NAME: {}", URL_NAME); } try { // Set up mail session mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator()) : Session.getDefaultInstance(dataSource); if (DEBUG) { DEBUGGER.debug("mailSession: {}", mailSession); } if (mailSession == null) { throw new MessagingException("Unable to configure email services"); } mailSession.setDebug(DEBUG); Store mailStore = mailSession.getStore(URL_NAME); mailStore.connect(); if (DEBUG) { DEBUGGER.debug("mailStore: {}", mailStore); } if (!(mailStore.isConnected())) { throw new MessagingException("Failed to connect to mail service. Cannot continue."); } mailFolder = mailStore.getFolder("inbox"); archiveFolder = mailStore.getFolder("archive"); if (!(mailFolder.exists())) { throw new MessagingException("Requested folder does not exist. Cannot continue."); } mailFolder.open(Folder.READ_WRITE); if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) { throw new MessagingException("Failed to open requested folder. Cannot continue"); } if (!(archiveFolder.exists())) { archiveFolder.create(Folder.HOLDS_MESSAGES); } Message[] mailMessages = mailFolder.getMessages(); if (mailMessages.length == 0) { throw new MessagingException("No messages were found in the provided store."); } emailMessages = new ArrayList<EmailMessage>(); for (Message message : mailMessages) { if (DEBUG) { DEBUGGER.debug("MailMessage: {}", message); } // validate the message here String messageId = message.getHeader("Message-ID")[0]; Long messageDate = message.getReceivedDate().getTime(); if (DEBUG) { DEBUGGER.debug("messageId: {}", messageId); DEBUGGER.debug("messageDate: {}", messageDate); } // only get emails for the last 24 hours // this should prevent us from pulling too // many emails if (messageDate >= TIME_PERIOD) { // process it Multipart attachment = (Multipart) message.getContent(); Map<String, InputStream> attachmentList = new HashMap<String, InputStream>(); for (int x = 0; x < attachment.getCount(); x++) { BodyPart bodyPart = attachment.getBodyPart(x); if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) { continue; } attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream()); } List<String> toList = new ArrayList<String>(); List<String> ccList = new ArrayList<String>(); List<String> bccList = new ArrayList<String>(); List<String> fromList = new ArrayList<String>(); for (Address from : message.getFrom()) { fromList.add(from.toString()); } if ((message.getRecipients(RecipientType.TO) != null) && (message.getRecipients(RecipientType.TO).length != 0)) { for (Address to : message.getRecipients(RecipientType.TO)) { toList.add(to.toString()); } } if ((message.getRecipients(RecipientType.CC) != null) && (message.getRecipients(RecipientType.CC).length != 0)) { for (Address cc : message.getRecipients(RecipientType.CC)) { ccList.add(cc.toString()); } } if ((message.getRecipients(RecipientType.BCC) != null) && (message.getRecipients(RecipientType.BCC).length != 0)) { for (Address bcc : message.getRecipients(RecipientType.BCC)) { bccList.add(bcc.toString()); } } EmailMessage emailMessage = new EmailMessage(); emailMessage.setMessageTo(toList); emailMessage.setMessageCC(ccList); emailMessage.setMessageBCC(bccList); emailMessage.setEmailAddr(fromList); emailMessage.setMessageAttachments(attachmentList); emailMessage.setMessageDate(message.getSentDate()); emailMessage.setMessageSubject(message.getSubject()); emailMessage.setMessageBody(message.getContent().toString()); emailMessage.setMessageSources(message.getHeader("Received")); if (DEBUG) { DEBUGGER.debug("emailMessage: {}", emailMessage); } emailMessages.add(emailMessage); if (DEBUG) { DEBUGGER.debug("emailMessages: {}", emailMessages); } } // archive it archiveFolder.open(Folder.READ_WRITE); if (archiveFolder.isOpen()) { mailFolder.copyMessages(new Message[] { message }, archiveFolder); message.setFlag(Flags.Flag.DELETED, true); } } } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } catch (MessagingException mex) { throw new MessagingException(mex.getMessage(), mex); } finally { try { if ((mailFolder != null) && (mailFolder.isOpen())) { mailFolder.close(true); } if ((archiveFolder != null) && (archiveFolder.isOpen())) { archiveFolder.close(false); } } catch (MessagingException mx) { ERROR_RECORDER.error(mx.getMessage(), mx); } } return emailMessages; }
From source file:org.pentaho.di.job.entries.getpop.MailConnection.java
/** * Check if a folder exists on server (only IMAP). * * @param foldername/* w w w. j a v a2 s . c om*/ * the name of the folder * @return true is folder exists */ public boolean folderExists(String foldername) { boolean retval = false; Folder dfolder = null; try { // Open destination folder dfolder = getRecursiveFolder(foldername); if (dfolder.exists()) { retval = true; } } catch (Exception e) { // Ignore errors } finally { try { if (dfolder != null) { dfolder.close(false); } } catch (Exception e) { /* Ignore */ } } return retval; }
From source file:com.zotoh.maedr.device.PopIO.java
private boolean conn() { if (_pop == null || !_pop.isConnected()) try {/* w ww . jav a2 s .c o 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:org.pentaho.di.job.entries.getpop.MailConnection.java
/** * Set destination folder/*w w w . j a va 2 s . com*/ * * @param foldername * destination foldername * @param createFolder * flag create folder if needed * @throws KettleException */ public void setDestinationFolder(String foldername, boolean createFolder) throws KettleException { try { String[] folderparts = foldername.split("/"); Folder f = this.getStore().getDefaultFolder(); // Open destination folder for (int i = 0; i < folderparts.length; i++) { f = f.getFolder(folderparts[i]); if (!f.exists()) { if (createFolder) { // Create folder f.create(Folder.HOLDS_MESSAGES); } else { throw new KettleException( BaseMessages.getString(PKG, "MailConnection.Error.FolderNotFound", foldername)); } } } this.destinationIMAPFolder = f; } catch (Exception e) { throw new KettleException(e); } }
From source file:br.unicamp.cotuca.dpd.pd12.acinet.vagalmail.servlet.Configuracoes.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); if (request.getRequestURI().contains("/pasta")) { String acao = request.getParameter("acao"), url = request.getParameter("url"), novo = request.getParameter("novo"); JSONObject obj = new JSONObject(); if (acao == null || url == null) { obj.put("erro", "Solicitao invlida"); obj.writeJSONString(response.getWriter()); return; }/*from w w w. j a v a2 s . c om*/ if ((acao.equals("renomear") || acao.equals("nova")) && novo == null) { obj.put("erro", "Solicitao invlida"); obj.writeJSONString(response.getWriter()); return; } try { Conta conta = (Conta) request.getSession().getAttribute("conta"); Store store = Logar.getImapStore(conta); Folder pasta = null; if (!acao.equals("nova")) { URLName urln = new URLName(url); pasta = store.getFolder(urln); if (pasta.isOpen()) pasta.close(false); } switch (acao) { case "renomear": if (pasta.renameTo(store.getFolder(novo))) { obj.put("sucesso", "Renomeado com sucesso"); } else { obj.put("erro", "Erro ao renomear a pasta"); } break; case "esvaziar": pasta.open(Folder.READ_WRITE); pasta.setFlags(1, pasta.getMessageCount(), new Flags(Flags.Flag.DELETED), true); pasta.expunge(); obj.put("sucesso", "Esvaziado com sucesso"); break; case "excluir": if (pasta.delete(true)) { obj.put("sucesso", "Excludo com sucesso"); } else { obj.put("erro", "Erro ao excluir a pasta"); } break; case "nova": pasta = store.getFolder(novo); if (!pasta.exists()) { if (pasta.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)) { obj.put("sucesso", "Criado com sucesso"); } else { obj.put("erro", "Erro ao criar a pasta"); } } else { obj.put("erro", "Erro ao criar a pasta"); } break; } } catch (MessagingException ex) { obj.put("erro", "Erro ao processar solicitao"); } obj.writeJSONString(response.getWriter()); return; } String metodo = request.getParameter("acao"); if (metodo == null) { return; } else if (metodo.equals("nova")) { EntityManager em = BD.getEntityManager(); try { em.getTransaction().begin(); Login usuario = Logar.getLogin(request.getSession()); Conta conta = new Conta(); conta.setEmail(request.getParameter("email")); conta.setImapHost(request.getParameter("imapHost")); conta.setImapPort(Integer.parseInt(request.getParameter("imapPort"))); conta.setImapPassword(request.getParameter("imapPassword")); conta.setImapUser(request.getParameter("imapLogin")); conta.setSmtpHost(request.getParameter("smtpHost")); conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort"))); conta.setSmtpPassword(request.getParameter("smtpPassword")); conta.setSmtpUser(request.getParameter("smtpLogin")); conta.setIdLogin(usuario); em.persist(conta); em.merge(usuario); em.getTransaction().commit(); em.refresh(conta); em.refresh(usuario); request.setAttribute("mensagem", "sucesso"); } catch (Logar.NaoAutenticadoException | PersistenceException ex) { em.getTransaction().rollback(); request.setAttribute("mensagem", "erro"); } request.getRequestDispatcher("/conf.jsp?metodo=nova").forward(request, response); } else if (metodo.equals("conta")) { EntityManager em = BD.getEntityManager(); try { em.getTransaction().begin(); Conta conta = (Conta) request.getSession().getAttribute("conta"); em.refresh(conta); conta.setEmail(request.getParameter("email")); conta.setImapHost(request.getParameter("imapHost")); conta.setImapPort(Integer.parseInt(request.getParameter("imapPort"))); conta.setImapPassword(request.getParameter("imapPassword")); conta.setImapUser(request.getParameter("imapLogin")); conta.setSmtpHost(request.getParameter("smtpHost")); conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort"))); conta.setSmtpPassword(request.getParameter("smtpPassword")); conta.setSmtpUser(request.getParameter("smtpLogin")); em.getTransaction().commit(); request.setAttribute("mensagem", "sucesso"); } catch (PersistenceException ex) { em.getTransaction().rollback(); request.setAttribute("mensagem", "erro"); } request.getRequestDispatcher("/conf.jsp?metodo=conta").forward(request, response); } else if (metodo.equals("senha")) { EntityManager em = BD.getEntityManager(); try { Login usuario = Logar.getLogin(request.getSession()); em.refresh(usuario); String senatu = request.getParameter("senAtu"), novasen = request.getParameter("senNova"), novasen2 = request.getParameter("senNova2"); if (novasen.equals(novasen2) && senatu.equals(usuario.getSenha())) { em.getTransaction().begin(); usuario.setSenha(novasen); em.getTransaction().commit(); request.setAttribute("mensagem", "sucesso"); } else { if (!novasen.equals(novasen2)) request.setAttribute("mensagem", "senneq"); else request.setAttribute("mensagem", "antsen"); } } catch (Logar.NaoAutenticadoException | PersistenceException ex) { em.getTransaction().rollback(); request.setAttribute("mensagem", "erro"); } request.getRequestDispatcher("/conf.jsp?metodo=senha").forward(request, response); } }
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 ww w .j a v a 2 s . c o 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) { } } }
From source file:com.funambol.email.items.manager.ImapEntityManager.java
/** * todo understand the type of a folder (holds folders and mails) * * @param name String//from w w w. ja v a 2 s.c om * @param parentId String * @param df DefaultFolder * @param idFolderSpace IdSpaceGenerator * @param source_uri String * @param principalId long * @return Folder * @throws EntityException */ public com.funambol.email.pdi.folder.Folder addFolder(String name, String parentId, DefaultFolder df, DBIDGenerator idFolderSpace, Map serverItems, String source_uri, long principalId, String username) throws EntityException { com.funambol.email.pdi.folder.Folder folderOut; ItemFolder itemFolder = null; String GUID = null; IMAPFolder f = null; // parent folder String parentFullpath; String fullpath; String role; String creationDate; EntityException finalExc = null; try { parentFullpath = this.ied.getFullPathFromGUID(parentId, source_uri, principalId, username); if (parentFullpath != null) { fullpath = parentFullpath + Def.SEPARATOR_FIRST + name; } else { fullpath = Def.SEPARATOR_FIRST + name; } if (log.isTraceEnabled()) { log.trace("addFolder FID:" + parentFullpath + " FMID:" + fullpath); } boolean isDefFolder = Utility.defaultFolderChecker(df, fullpath); if (isDefFolder) { GUID = Utility.getDefaultFolderId(df, fullpath); } else { f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(parentFullpath); timeStart = System.currentTimeMillis(); f.open(Folder.READ_WRITE); Folder folderToInsert = f.getFolder(name); int type = 0; // set the right folder type if (!folderToInsert.exists()) { GUID = this.ied.addFolder(fullpath, parentId, folderToInsert, type, idFolderSpace, source_uri, principalId, username); } // set the values for the post update operation SyncItemInfo sii = createInfo(GUID); // update email to the servetItems list this.ied.addItemInServerItems(sii, serverItems); } role = Utility.getFolderRole(name, this.imsw.getDefaultFolder()); creationDate = Utility.getFolderCreationDate(); itemFolder = setItemFolder(GUID, name, parentId, role, creationDate); } catch (MessagingException me) { throw new EntityException("Error searching folder", me); } catch (EntityException ee) { throw new EntityException("Error creating folder", ee); } finally { if (f != null) { try { if (f.isOpen()) { f.close(true); timeStop = System.currentTimeMillis(); if (log.isTraceEnabled()) { log.trace("insertFolder Execution Time: " + (timeStop - timeStart) + " ms"); } } } catch (MessagingException me) { finalExc = new EntityException(me); } } } if (finalExc != null) { throw finalExc; } try { folderOut = createFoundationFolder(itemFolder); } catch (Exception e) { throw new EntityException(e); } return folderOut; }
From source file:net.wastl.webmail.server.WebMailSession.java
public void addFolder(String toid, String name, boolean holds_messages, boolean holds_folders) throws MessagingException { Folder parent = getFolder(toid);/*from w w w .j a va 2 s . c o m*/ Folder folder = parent.getFolder(name); if (!folder.exists()) { int type = 0; if (holds_messages) { type += Folder.HOLDS_MESSAGES; } if (holds_folders) { type += Folder.HOLDS_FOLDERS; } folder.create(type); } // Should be called from FolderSetup Plugin //refreshFolderInformation(); }
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 2s . c o 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:net.wastl.webmail.server.WebMailSession.java
/** * Refresh Information about folders.// w w w.jav a 2 s . c om * Tries to connect folders that are not yet connected. * * @doCount display message counts for user */ public void refreshFolderInformation(boolean subscribed_only, boolean doCount) { /* Right now, doCount corresponds exactly to subscribed_only. * When we add a user preference setting or one-time action, * to present messages from all folders, we will have * subscribed_only false and doCount true. */ //log.fatal("Invoking refreshFolderInformation(boolean, boolean)", //new Throwable("Thread Dump")); FOR DEBUGGING setEnv(); if (folders == null) folders = new Hashtable<String, Folder>(); Folder rootFolder = null; String cur_mh_id = ""; Enumeration mailhosts = user.mailHosts(); int max_depth = 0; int folderType; while (mailhosts.hasMoreElements()) { cur_mh_id = (String) mailhosts.nextElement(); MailHostData mhd = user.getMailHost(cur_mh_id); URLName url = new URLName(mhd.getHostURL()); Element mailhost = model.createMailhost(mhd.getName(), mhd.getID(), url.toString()); int depth = 0; try { rootFolder = getRootFolder(cur_mh_id); try { rootFolder.setSubscribed(true); } catch (MessagingException ex) { // Only IMAP supports subscription log.warn("Folder.setSubscribed failed. " + "Probably a non-supporting mail service: " + ex); } } catch (MessagingException ex) { mailhost.setAttribute("error", ex.getMessage()); log.warn("Failed to connect and get Root folder from (" + url + ')', ex); return; } try { depth = getFolderTree(rootFolder.getFolder("INBOX"), mailhost, subscribed_only, doCount); log.debug("Loaded INBOX folders below Root to a depth of " + depth); String extraFolderPath = ((imapBasedir == null) ? "~" : imapBasedir) + mhd.getLogin(); //String extraFolderPath = "/home/" + mhd.getLogin(); Folder nonInboxBase = rootFolder.getFolder(extraFolderPath); log.debug("Trying extra base dir " + nonInboxBase.getFullName()); if (nonInboxBase.exists()) { folderType = nonInboxBase.getType(); if ((folderType & Folder.HOLDS_MESSAGES) != 0) { // Can only Subscribe to Folders which may hold Msgs. nonInboxBase.setSubscribed(true); if (!nonInboxBase.isSubscribed()) log.error("A bug in JavaMail or in the server is " + "preventing subscription to '" + nonInboxBase.getFullName() + "' on '" + url + "'. Folders will not be visible."); } int extraDepth = extraDepth = getFolderTree(nonInboxBase, mailhost, subscribed_only, doCount); if (extraDepth > depth) depth = extraDepth; log.debug("Loaded additional folders from below " + nonInboxBase.getFullName() + " with max depth of " + extraDepth); } } catch (Exception ex) { if (!url.getProtocol().startsWith("pop")) mailhost.setAttribute("error", ex.getMessage()); log.warn("Failed to fetch child folders from (" + url + ')', ex); } if (depth > max_depth) max_depth = depth; model.addMailhost(mailhost); } model.setStateVar("max folder depth", (1 + max_depth) + ""); }