List of usage examples for javax.mail Folder open
public abstract void open(int mode) throws MessagingException;
From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java
/** * {@inheritDoc}//from w w w. ja va2s . co m */ @Override public SampleResult sample(Entry e) { SampleResult parent = new SampleResult(); boolean isOK = false; // Did sample succeed? final boolean deleteMessages = getDeleteMessages(); final String serverProtocol = getServerType(); parent.setSampleLabel(getName()); String samplerString = toString(); parent.setSamplerData(samplerString); /* * Perform the sampling */ parent.sampleStart(); // Start timing try { // Create empty properties Properties props = new Properties(); if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$ if (isEnforceStartTLS()) { // Requires JavaMail 1.4.2+ props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$ } } if (isTrustAllCerts()) { if (isUseSSL()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$ props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } else if (isUseLocalTrustStore()) { File truststore = new File(getTrustStoreToUse()); log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse()); log.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (isUseSSL()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } else if (isUseStartTLS()) { // Requires JavaMail 1.4.2+ props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ new LocalTrustStoreSSLSocketFactory(truststore)); props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$ } } // Get session Session session = Session.getInstance(props, null); // Get the store Store store = session.getStore(serverProtocol); store.connect(getServer(), getPortAsInt(), getUserName(), getPassword()); // Get folder Folder folder = store.getFolder(getFolder()); if (deleteMessages) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } final int messageTotal = folder.getMessageCount(); int n = getNumMessages(); if (n == ALL_MESSAGES || n > messageTotal) { n = messageTotal; } // Get directory Message[] messages = folder.getMessages(1, n); StringBuilder pdata = new StringBuilder(); pdata.append(messages.length); pdata.append(" messages found\n"); parent.setResponseData(pdata.toString(), null); parent.setDataType(SampleResult.TEXT); parent.setContentType("text/plain"); // $NON-NLS-1$ final boolean headerOnly = getHeaderOnly(); busy = true; for (Message message : messages) { StringBuilder cdata = new StringBuilder(); SampleResult child = new SampleResult(); child.sampleStart(); cdata.append("Message "); // $NON-NLS-1$ cdata.append(message.getMessageNumber()); child.setSampleLabel(cdata.toString()); child.setSamplerData(cdata.toString()); cdata.setLength(0); final String contentType = message.getContentType(); child.setContentType(contentType);// Store the content-type child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default child.setEncodingAndType(contentType);// Parse the content-type if (isStoreMimeMessage()) { // Don't save headers - they are already in the raw message ByteArrayOutputStream bout = new ByteArrayOutputStream(); message.writeTo(bout); child.setResponseData(bout.toByteArray()); // Save raw message child.setDataType(SampleResult.TEXT); } else { @SuppressWarnings("unchecked") // Javadoc for the API says this is OK Enumeration<Header> hdrs = message.getAllHeaders(); while (hdrs.hasMoreElements()) { Header hdr = hdrs.nextElement(); String value = hdr.getValue(); try { value = MimeUtility.decodeText(value); } catch (UnsupportedEncodingException uce) { // ignored } cdata.append(hdr.getName()).append(": ").append(value).append("\n"); } child.setResponseHeaders(cdata.toString()); cdata.setLength(0); if (!headerOnly) { appendMessageData(child, message); } } if (deleteMessages) { message.setFlag(Flags.Flag.DELETED, true); } child.setResponseOK(); if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called. child.sampleEnd(); } parent.addSubResult(child); } // Close connection folder.close(true); store.close(); parent.setResponseCodeOK(); parent.setResponseMessageOK(); isOK = true; } catch (NoClassDefFoundError | IOException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString()); } catch (MessagingException ex) { log.debug("", ex);// No need to log normally, as we set the status parent.setResponseCode("500"); // $NON-NLS-1$ parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$ } finally { busy = false; } if (parent.getEndTime() == 0) {// not been set by any child samples parent.sampleEnd(); } parent.setSuccessful(isOK); return parent; }
From source file:org.zilverline.core.IMAPCollection.java
private final boolean indexFolder(IndexWriter writer, Folder thisFolder) throws MessagingException { if (stopRequested) { log.info("Indexing stops, due to request"); return false; }/*w w w . java2s . c o m*/ if ((thisFolder.getType() & Folder.HOLDS_MESSAGES) != 0) { thisFolder.open(Folder.READ_ONLY); Message[] messages = thisFolder.getMessages(); // get refs to all msgs if (messages == null) { // dummy messages = new Message[0]; } thisFolder.fetch(messages, PROFILE); // fetch headers log.debug("FOLDER: " + thisFolder.getFullName() + " messages=" + messages.length); for (int i = 0; i < messages.length; i++) { try { String msgID = null; if (messages[i] instanceof MimeMessage) { MimeMessage mm = (MimeMessage) messages[i]; msgID = mm.getMessageID(); } if (!md5DocumentCache.contains(msgID)) { log.debug("new message added for message: " + msgID); final Document doc = new Document(); doc.add(Field.Keyword(F_FOLDER, thisFolder.getFullName())); doc.add(Field.Keyword("collection", name)); // index this message indexMessage(doc, messages[i]); // add it writer.addDocument(doc); md5DocumentCache.add(msgID); } else { log.debug("existing message skipped for message: " + msgID); } } catch (Exception ioe) { // can be side effect of hosed up mail headers log.warn("Bad Message: " + messages[i], ioe); continue; } } } // recurse if possible if ((thisFolder.getType() & Folder.HOLDS_FOLDERS) != 0) { Folder[] far = thisFolder.list(); if (far != null) { for (int i = 0; i < far.length; i++) { indexFolder(writer, far[i]); } } } if (thisFolder.isOpen()) { log.debug("Closing folder: " + thisFolder.getFullName()); thisFolder.close(false); // false => do not expunge } return true; }
From source file:org.nuxeo.cm.event.MailInjectionListener.java
public void handleEvent(Event event) throws ClientException { MailService mailService = Framework.getService(MailService.class); MessageActionPipe pipe = mailService.getPipe(MAILBOX_PIPE); Visitor visitor = new Visitor(pipe); Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader()); Folder rootFolder = null; try (CoreSession session = CoreInstance.openCoreSessionSystem(null)) { // initialize context ExecutionContext initialExecutionContext = new ExecutionContext(); initialExecutionContext.put(AbstractCaseManagementMailAction.CORE_SESSION_KEY, session); initialExecutionContext.put(AbstractCaseManagementMailAction.MIMETYPE_SERVICE_KEY, Framework.getService(MimetypeRegistry.class)); initialExecutionContext.put(AbstractCaseManagementMailAction.CASEMANAGEMENT_SERVICE_KEY, Framework.getService(CaseDistributionService.class)); // open store Store store = mailService.getConnectedStore(IMPORT_MAILBOX); rootFolder = store.getFolder(INBOX); rootFolder.open(Folder.READ_WRITE); Flags flags = new Flags(); flags.add(Flag.SEEN);//w w w . j av a 2 s .c om SearchTerm term = new FlagTerm(flags, false); Message[] unreadMessages = rootFolder.search(term); // perform import visitor.visit(unreadMessages, initialExecutionContext); // save session session.save(); if (rootFolder.isOpen()) { try { rootFolder.close(true); } catch (MessagingException e) { log.error(e.getMessage(), e); } } } catch (MessagingException e) { log.error(e, e); } }
From source file:EmailBean.java
private void handleMessages(HttpServletRequest request, PrintWriter out) throws IOException, ServletException { HttpSession httpSession = request.getSession(); String user = (String) httpSession.getAttribute("user"); String password = (String) httpSession.getAttribute("pass"); String popAddr = (String) httpSession.getAttribute("pop"); Store popStore = null;/*from ww w . j a v a 2 s .c om*/ Folder folder = null; if (!check(popAddr)) popAddr = EmailBean.DEFAULT_SERVER; try { if ((!check(user)) || (!check(password))) throw new ServletException("A valid username and password is required to check email."); Properties properties = System.getProperties(); Session session = Session.getDefaultInstance(properties); popStore = session.getStore("pop3"); popStore.connect(popAddr, user, password); folder = popStore.getFolder("INBOX"); if (!folder.exists()) throw new ServletException("An 'INBOX' folder does not exist for the user."); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); int msgLen = messages.length; if (msgLen == 0) out.println("<h2>The INBOX folder does not yet contain any email messages.</h2>"); for (int i = 0; i < msgLen; i++) { displayMessage(messages[i], out); out.println("<br /><br />"); } } catch (Exception exc) { out.println("<h2>Sorry, an error occurred while accessing the email messages.</h2>"); out.println(exc.toString()); } finally { try { if (folder != null) folder.close(false); if (popStore != null) popStore.close(); } catch (Exception e) { } } }
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
@Override public AccountSummary fetchAccountSummaryFromStore(MailStoreConfiguration config, String username, String mailAccount, String folder, int start, int max) { Authenticator auth = credentialsProvider.getAuthenticator(); AccountSummary summary;//from www.j av a2s. co m Folder inbox = null; try { // Retrieve user's folder Session session = openMailSession(config, auth); inbox = getUserInbox(session, folder); inbox.open(Folder.READ_ONLY); long startTime = System.currentTimeMillis(); List<EmailMessage> messages = getEmailMessages(inbox, start, max, session); if (log.isDebugEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; int messagesToDisplayCount = messages.size(); log.debug("Finished looking up email messages. Inbox size: " + inbox.getMessageCount() + " Unread message count: " + inbox.getUnreadMessageCount() + " Total elapsed time: " + elapsedTime + "ms " + " Time per message in inbox: " + (inbox.getMessageCount() == 0 ? 0 : (elapsedTime / inbox.getMessageCount())) + "ms" + " Time per displayed message: " + (messagesToDisplayCount == 0 ? 0 : (elapsedTime / messagesToDisplayCount)) + "ms"); } IEmailLinkService linkService = linkServiceRegistry.getEmailLinkService(config.getLinkServiceKey()); String inboxUrl = null; if (linkService != null) { inboxUrl = linkService.getInboxUrl(config); } // Initialize account information with information retrieved from inbox summary = new AccountSummary(inboxUrl, messages, inbox.getUnreadMessageCount(), inbox.getMessageCount(), start, max, isDeleteSupported(inbox), getQuota(inbox)); if (log.isDebugEnabled()) { log.debug("Successfully retrieved email AccountSummary"); } return summary; } catch (MailAuthenticationException mae) { // We used just to allow this exception to percolate up the chain, // but we learned that the entire stack trace gets written to // Catalina.out (by 3rd party code). Since this is a common // occurrence, it causes space issues. return new AccountSummary(mae); } catch (MessagingException me) { log.error("Exception encountered while retrieving account info", me); throw new EmailPreviewException(me); } catch (IOException e) { log.error("Exception encountered while retrieving account info", e); throw new EmailPreviewException(e); } catch (ScanException e) { log.error("Exception encountered while retrieving account info", e); throw new EmailPreviewException(e); } catch (PolicyException e) { log.error("Exception encountered while retrieving account info", e); throw new EmailPreviewException(e); } finally { if (inbox != null) { try { inbox.close(false); } catch (Exception e) { log.warn("Can't close correctly javamail inbox connection"); } try { inbox.getStore().close(); } catch (Exception e) { log.warn("Can't close correctly javamail store connection"); } } } }
From source file:org.openadaptor.auxil.connector.mail.MailConnection.java
/** * Opens the named folder in READ/WRITE mode * * @throws MessagingException if there is a comms error or if the folder could not * be found or we failed to create it/*from w w w .j a v a2 s . co m*/ */ public Folder openFolder(String fldr, boolean create) throws MessagingException { if (store == null || !store.isConnected()) connect(); Folder f = store.getFolder(fldr); log.debug("Folder [" + fldr + "] exists? " + f.exists()); // Note that a Folder object is returned even if the named folder does not // physically exist on the Store so we have to test for it explicitly. if (!f.exists()) { // we've not been asked to create the folder so this is an error if (!create) throw new MessagingException("Error opening folder [" + fldr + "]: Folder not found"); // try to create the folder if (!f.create(Folder.HOLDS_MESSAGES)) throw new MessagingException("Failed to create folder [" + fldr + "]"); log.info("Created folder [" + fldr + "]"); } f.open(Folder.READ_WRITE); log.debug("Folder [" + fldr + "] opened"); return f; }
From source file:com.liferay.mail.imap.IMAPAccessor.java
public Folder openFolder(Folder jxFolder) throws MailException { try {//from www . j a va 2s . c o m if (jxFolder.isOpen()) { return jxFolder; } jxFolder.open(Folder.READ_WRITE); return jxFolder; } catch (MessagingException me) { throw new MailException(me); } }
From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
@Override public EmailMessage getMessage(MailStoreConfiguration config, String messageId) { Authenticator auth = credentialsProvider.getAuthenticator(); Folder inbox = null; try {/*from w w w . j a v a 2 s. com*/ int mode = config.getMarkMessagesAsRead() ? Folder.READ_WRITE : Folder.READ_ONLY; // Retrieve user's inbox Session session = openMailSession(config, auth); inbox = getUserInbox(session, config.getInboxFolderName()); inbox.open(mode); Message message; if (inbox instanceof UIDFolder) { message = ((UIDFolder) inbox).getMessageByUID(Long.parseLong(messageId)); } else { message = inbox.getMessage(Integer.parseInt(messageId)); } boolean unread = !message.isSet(Flags.Flag.SEEN); if (config.getMarkMessagesAsRead()) { message.setFlag(Flag.SEEN, true); } EmailMessage emailMessage = wrapMessage(message, true, session); if (!config.getMarkMessagesAsRead()) { // NOTE: This is more than a little bit annoying. Apparently // the mere act of accessing the body content of a message in // Javamail flags the in-memory representation of that message // as SEEN. It does *nothing* to the mail server (the message // is still unread in the SOR), but it wreaks havoc on local // functions that key off that value and expect it to be // accurate. We're obligated, therefore, to restore the value // to what it was before the call to wrapMessage(). emailMessage.setUnread(unread); } return emailMessage; } catch (MessagingException e) { log.error("Messaging exception while retrieving individual message", e); } catch (IOException e) { log.error("IO exception while retrieving individual message", e); } catch (ScanException e) { log.error("AntiSamy scanning exception while retrieving individual message", e); } catch (PolicyException e) { log.error("AntiSamy policy exception while retrieving individual message", e); } finally { if (inbox != null) { try { inbox.close(false); } catch (Exception e) { log.warn("Can't close correctly javamail inbox connection"); } try { inbox.getStore().close(); } catch (Exception e) { log.warn("Can't close correctly javamail store connection"); } } } return null; }
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; }//w w w . j av a 2s .co m 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:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void createInitialIMAPTestdata(final Properties props, final String user, final String password, final int count, final boolean deleteall) throws MessagingException { final Session session = Session.getInstance(props); final Store store = session.getStore(); store.connect(user, password);//from w ww.j a va 2 s. co m checkStoreForTestConnection(store); final Folder root = store.getDefaultFolder(); final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS"); final Folder testrootl2 = testroot.getFolder("Level(2!"); if (deleteall) { deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password); if (testroot.exists()) { testroot.delete(true); } final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS"); if (testrootenamed.exists()) { testrootenamed.delete(true); } } if (!testroot.exists()) { testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES); testroot.open(Folder.READ_WRITE); testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES); testrootl2.open(Folder.READ_WRITE); } final Folder inbox = root.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); final Message[] msgs = new Message[count]; for (int i = 0; i < count; i++) { final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(EMAIL_TO)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS)); message.setSubject(EMAIL_SUBJECT + "::" + i); message.setText(EMAIL_TEXT + "::" + SID++); message.setSentDate(new Date()); msgs[i] = message; } inbox.appendMessages(msgs); testroot.appendMessages(msgs); testrootl2.appendMessages(msgs); IMAPUtils.close(inbox); IMAPUtils.close(testrootl2); IMAPUtils.close(testroot); IMAPUtils.close(store); }