List of usage examples for javax.mail Folder close
public abstract void close(boolean expunge) throws MessagingException;
From source file:com.seleniumtests.connectors.mails.ImapClient.java
/** * Returns the number of messages on the server * /*from w w w . j a va 2 s.c o m*/ * @param folderName * @return * @throws MessagingException */ private Integer getMessageNumber(String folderName) throws MessagingException { // Get folder Folder folder = store.getFolder(folderName); folder.open(Folder.READ_ONLY); Integer messageCount = folder.getMessageCount(); folder.close(false); return messageCount; }
From source file:edu.stanford.muse.email.ImapPopEmailStore.java
public void computeFoldersAndCounts(String cacheDir /*unused */) throws MessagingException { if (store == null) connect();/*from www . ja v a 2s .c o m*/ if (!store.isConnected()) connect(); doneReadingFolderCounts = false; this.folderInfos = new ArrayList<FolderInfo>(); if ("pop3".equals(connectOptions.protocol) || "pop3s".equals(connectOptions.protocol)) { Folder f = store.getDefaultFolder(); f = f.getFolder("INBOX"); f.open(Folder.READ_ONLY); int count = f.getMessageCount(); f.close(false); this.folderInfos.add(new FolderInfo(getAccountID(), "INBOX", "INBOX", count)); } else collect_folder_names(store, this.folderInfos, store.getDefaultFolder()); folderBeingScanned = ""; if (connectOptions.server.endsWith(".pobox.stanford.edu")) this.folderInfos.add(new FolderInfo(getAccountID(), "INBOX", "INBOX", 0)); // hack for stanford imap, it lists INBOX as a dir folder! TOFIX doneReadingFolderCounts = true; }
From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java
/** * {@inheritDoc}/*from w w w . java2 s . c om*/ * * @throws MessagingException * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String) */ public Message read(String folder, String messageid) throws MessagingException { Store store = getJavamailStore(); store.connect(); Folder mailFolder = store.getDefaultFolder().getFolder(folder); mailFolder.open(Folder.READ_ONLY); Message[] messages = mailFolder.search(new MessageIDTerm(messageid)); mailFolder.close(false); store.close(); if (messages.length > 0) { return messages[0]; } return null; }
From source file:com.ikon.util.MailUtils.java
/** * Test IMAP connection//ww w. j a va 2 s . co m */ public static void testConnection(MailAccount ma) throws IOException { log.debug("testConnection({})", ma); Session session = Session.getDefaultInstance(getProperties()); Store store = null; Folder folder = null; try { store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); folder.close(false); } catch (NoSuchProviderException e) { throw new IOException(e.getMessage()); } catch (MessagingException e) { throw new IOException(e.getMessage()); } finally { // Try to close folder if (folder != null && folder.isOpen()) { try { folder.close(false); } catch (MessagingException e) { throw new IOException(e.getMessage()); } } // Try to close store if (store != null) { try { store.close(); } catch (MessagingException e) { throw new IOException(e.getMessage()); } } } log.debug("testConnection: void"); }
From source file:com.yfiton.notifiers.email.EmailNotifierTest.java
private boolean checkEmailReception(String subject, String host, String username, String password) throws MessagingException { Properties properties = new Properties(); properties.put("mail.store.protocol", "imaps"); Session session = Session.getInstance(properties); Store store = null;/*w w w .j a va 2s .co m*/ try { store = session.getStore("imaps"); store.connect(host, username, password); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); for (Message message : messages) { if (message.getSubject().equals(subject)) { message.setFlag(Flags.Flag.DELETED, true); return true; } } inbox.close(true); } finally { try { if (store != null) { store.close(); } } catch (MessagingException e) { e.printStackTrace(); } } return false; }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method read e-mails from Gmail inbox and find whether the notification of particular type is found. * * @param notificationType Notification types supported by publisher and store. * @return whether email is found for particular type. * @throws Exception// w ww. j av a 2s . com */ public static boolean readGmailInboxForNotification(String notificationType) throws Exception { boolean isNotificationMailAvailable = false; long waitTime = 10000; Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Thread.sleep(waitTime); long startTime = System.currentTimeMillis(); long endTime = 0; int count = 1; while (endTime - startTime < 180000 && !isNotificationMailAvailable) { Message[] messages = inbox.getMessages(); for (Message message : messages) { if (!message.isExpunged()) { try { log.info("Mail Subject:- " + message.getSubject()); if (message.getSubject().contains(notificationType)) { isNotificationMailAvailable = true; } // Optional : deleting the mail message.setFlag(Flags.Flag.DELETED, true); } catch (MessageRemovedException e) { log.error("Could not read the message subject. Message is removed from inbox"); } } } endTime = System.currentTimeMillis(); Thread.sleep(waitTime); endTime += count * waitTime; count++; } inbox.close(true); store.close(); return isNotificationMailAvailable; }
From source file:nl.ordina.bag.etl.mail.loader.POP3MutatiesFileLoader.java
@Override public void processMessages() { try {// w ww. j a va 2 s. c om Session session = Session.getDefaultInstance(new Properties(), null); Store store = session.getStore(protocol); if (port == 0) store.connect(host, username, password); else store.connect(host, port, username, password); Folder folder = store.getFolder(folderName); if (folder == null) throw new RuntimeException("Folder " + folderName + " not found!"); folder.open(Folder.READ_WRITE); try { Message[] messages = folder.getMessages(); for (Message message : messages) { backup(message); messageHandler.handle(message); message.setFlags(new Flags(Flags.Flag.DELETED), true); } } finally { folder.close(true); store.close(); } } catch (MessagingException | IOException | JAXBException e) { throw new ProcessingException(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 .ja v a 2 s . 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:org.wso2.es.ui.integration.util.ESUtil.java
/** * To check if a e-mail exists with a given subject * * @param smtpPropertyFile smtp property file path * @param password password//from www .j a va2 s .c om * @param email email address * @param subject email subject * @return if the mail exist * @throws java.io.IOException * @throws MessagingException * @throws InterruptedException */ public static String readEmail(String smtpPropertyFile, String password, String email, String subject) throws MessagingException, InterruptedException, IOException { Properties props = new Properties(); String message = null; Folder inbox = null; Store store = null; FileInputStream inputStream = null; try { inputStream = new FileInputStream(new File(smtpPropertyFile)); props.load(inputStream); Session session = Session.getDefaultInstance(props, null); store = session.getStore(IMAPS); store.connect(SMTP_GMAIL_COM, email, password); inbox = store.getFolder(INBOX); inbox.open(Folder.READ_ONLY); message = getMailWithSubject(inbox, subject); } catch (MessagingException e) { LOG.error(getErrorMessage(email), e); throw e; } catch (InterruptedException e) { LOG.error(getErrorMessage(email), e); throw e; } catch (FileNotFoundException e) { LOG.error(getErrorMessage(email), e); throw e; } catch (IOException e) { LOG.error(getErrorMessage(email), e); throw e; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { LOG.error("Input stream closing failed"); } } if (inbox != null) { try { inbox.close(true); } catch (MessagingException e) { LOG.error("Inbox closing failed"); } } if (store != null) { try { store.close(); } catch (MessagingException e) { LOG.error("Message store closing failed"); } } } return message; }
From source file:nl.ordina.bag.etl.mail.loader.IMAPMutatiesFileLoader.java
@Override public void processMessages() { try {/*from w w w . j a va 2 s . c om*/ Session session = Session.getDefaultInstance(new Properties(), null); Store store = session.getStore(protocol); if (port == 0) store.connect(host, username, password); else store.connect(host, port, username, password); Folder folder = store.getFolder(folderName); if (folder == null) throw new RuntimeException("Folder " + folderName + " not found!"); folder.open(Folder.READ_WRITE); try { FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Message messages[] = folder.search(ft); for (Message message : messages) { messageHandler.handle(message); message.setFlags(new Flags(Flags.Flag.SEEN), true); } } finally { folder.close(true); store.close(); } } catch (MessagingException | IOException | JAXBException e) { throw new ProcessingException(e); } }