List of usage examples for javax.mail Store close
public synchronized void close() 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 w w w. ja v a2 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.webguitoolkit.messagebox.mail.MailChannel.java
/** * /*from ww w . jav a2 s . c om*/ */ @Override public List<IMessage> receive(boolean clear) { List<IMessage> result = new ArrayList<IMessage>(); try { String user = properties.getProperty("pop3.login.user"); String password = properties.getProperty("pop3.login.password"); String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port")); pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port")); URLName url = new URLName("pop3", properties.getProperty("pop3.host"), Integer.valueOf(properties.getProperty("pop3.port")), "", user, password); Session session = Session.getInstance(pop3Props, null); Store store = new POP3SSLStore(session, url); store.connect(); // Open the Folder Folder folder = store.getDefaultFolder(); folder = folder.getFolder("INBOX"); if (folder == null) { throw new RuntimeException("Invalid folder INBOX"); } // try to open read/write and if that fails try read-only try { folder.open(Folder.READ_WRITE); } catch (MessagingException ex) { folder.open(Folder.READ_ONLY); } int count = folder.getMessageCount(); // Message numbers start at 1 for (int i = 1; i <= count; i++) { // Get a message by its sequence number Message m = folder.getMessage(i); Address[] from = m.getFrom(); String type = from[0].getType(); IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m)); result.add(message); // delete message ? if (clear) m.setFlag(Flags.Flag.DELETED, true); } // "true" actually deletes flagged messages from folder folder.close(clear); store.close(); } catch (Exception e) { throw new RuntimeException(e); } return result; }
From source file:com.silverpeas.mailinglist.service.job.TestZimbraConnection.java
@Test public void testOpenImapConnection() { URL url = this.getClass().getClassLoader().getResource("truststore.jks"); String path = url.getPath();//from w ww . java2 s.c om System.setProperty("javax.net.ssl.trustStore", path); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); Store mailAccount = null; Folder inbox = null; Session mailSession = Session.getInstance(System.getProperties()); try { mailSession.setDebug(true); mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol")); mailAccount.connect(props.getProperty("mail.server.host"), Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"), props.getProperty("mail.server.password")); inbox = mailAccount.getFolder("INBOX"); if (inbox == null) { throw new MessagingException("No POP3 INBOX"); } // -- Open the folder for read write -- inbox.open(Folder.READ_WRITE); // -- Get the message wrappers and process them -- Message[] msgs = inbox.getMessages(); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.FLAGS); inbox.fetch(msgs, profile); } catch (MessagingException mex) { SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex); } catch (Exception mex) { SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex); } finally { // -- Close down nicely -- try { if (inbox != null) { inbox.close(false); } if (mailAccount != null) { mailAccount.close(); } } catch (Exception ex2) { SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", ex2); } } }
From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java
private Object getMessage(String requestMsgId) { Session session = Session.getInstance(props, null); session.setDebug(log.isTraceEnabled()); Store store = null; try {/*from www .ja v a 2s.c o m*/ store = session.getStore("pop3"); store.connect(username, password); Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER); folder.open(Folder.READ_WRITE); Message[] msgs = folder.getMessages(); log.debug(msgs.length + " replies in reply mailbox"); for (Message m : msgs) { String[] inReplyTo = m.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO); log.debug("Got reply to : " + Arrays.toString(inReplyTo)); if (inReplyTo != null && inReplyTo.length > 0) { for (int j = 0; j < inReplyTo.length; j++) { if (requestMsgId.equals(inReplyTo[j])) { m.setFlag(Flags.Flag.DELETED, true); return m.getContent(); } } } m.setFlag(Flags.Flag.DELETED, true); } folder.close(true); } catch (Exception e) { e.printStackTrace(); } finally { if (store != null) { try { store.close(); } catch (MessagingException ignore) { } store = null; } } return null; }
From source file:org.zilverline.core.IMAPCollection.java
/** * Sets existsOnDisk based on whether the collection (contentDir) actually (now) sits on disk. * /*from www . java 2s .c o 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: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; Folder folder = null;/*from w w w.java2s . co m*/ 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:com.robin.utilities.Utilities.java
/** * A utility that waits for a gmail mailbox to receive a new message with * according to a given SearchTerm. Only "Not seen" messages are searched, * and all match is set as SEEN, but just the first occurrence of the * matching message is returned./*from w w w .j a va2s . c om*/ * @param username the mailbox owner's user name (no @gmail.com required). * @param pass the user password protecting this mailbox * @param st the SearchTerm built to filter messages * @param timeoutMessage the message to show when no such mail found within * timeout * @param timeout The maximum amount of time to wait in milliseconds. * @return a last from the new messages thats match the st conditions */ public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st, final String timeoutMessage, final long timeout) { String host = "imap.gmail.com"; final long retryTime = 1000; Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.put("mail.imaps.ssl.trust", "*"); EMail email = null; Session session = Session.getDefaultInstance(props, null); try { Store store = session.getStore("imaps"); store.connect(host, username, pass); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_WRITE); FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox) .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS) .withMessage(timeoutMessage); email = waitForMail.until(new Function<Folder, EMail>() { @Override public EMail apply(final Folder inbox) { EMail email = null; FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); SearchTerm sst = new AndTerm(ft, st); try { inbox.getMessageCount(); Message[] messages = inbox.search(sst); for (Message message : messages) { message.setFlag(Flag.SEEN, true); } if (messages.length > 0) { return new EMail(messages[0]); } } catch (MessagingException e) { Assert.fail(e.getMessage()); } return email; } }); inbox.close(false); store.close(); } catch (MessagingException e) { Assert.fail(e.getMessage()); } return email; }
From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java
@Override public ArrayList<FolderItem> getFolderTree() throws MessagingException { getLogger().debug("getFolderTree"); assert (getMailSource() != null); ArrayList<FolderItem> folderItems = new ArrayList<FolderItem>(); Store store = getJavamailStore(); store.connect();//from w w w. j a va 2 s. co m Folder defaultFolder = store.getDefaultFolder(); FolderItem item = new FolderItem(); item.setIndex(0); item.setLevel(0); item.setName(defaultFolder.getName()); item.setFullName(defaultFolder.getFullName()); if ((defaultFolder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) { item.setMessageCount(defaultFolder.getMessageCount()); item.setUnreadMessageCount(defaultFolder.getUnreadMessageCount()); item.setNewMessageCount(defaultFolder.getNewMessageCount()); } Folder[] folders = defaultFolder.list("*"); if (ArrayUtils.isEmpty(folders)) { folders = defaultFolder.list(); } getLogger().debug("Found folders {}", ArrayUtils.toString(folders)); int index = 1; int level = 1; // TODO not really managing folders here, just listing them for (Folder folder : folders) { item = new FolderItem(); item.setIndex(index); item.setLevel(level); item.setName(folder.getName()); item.setFullName(folder.getFullName()); if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) { item.setMessageCount(folder.getMessageCount()); item.setUnreadMessageCount(folder.getUnreadMessageCount()); item.setNewMessageCount(folder.getNewMessageCount()); folderItems.add(item); } } store.close(); return folderItems; }
From source file:org.alfresco.repo.imap.RemoteLoadTester.java
public void testListSequence() { System.out.println(String.format("Connecting to remote server '%s'", REMOTE_HOST)); Properties props = System.getProperties(); props.setProperty("mail.imap.partialfetch", "false"); Session session = Session.getDefaultInstance(props, null); Store store = null; long startTime = 0; long endTime = 0; try {/*from ww w . j av a2s. co m*/ store = session.getStore("imap"); store.connect(REMOTE_HOST, ADMIN_USER_NAME, ADMIN_USER_NAME); Folder[] folders = null; startTime = System.currentTimeMillis(); folders = store.getDefaultFolder().list(""); endTime = System.currentTimeMillis(); System.out.println(String.format("LIST '', folders.length = %d, execTime = %d sec", folders.length, (endTime - startTime) / 1000)); startTime = System.currentTimeMillis(); folders = store.getDefaultFolder().list("*"); endTime = System.currentTimeMillis(); System.out.println(String.format("LIST *, folders.length = %d, execTime = %d sec", folders.length, (endTime - startTime) / 1000)); startTime = System.currentTimeMillis(); folders = store.getDefaultFolder().listSubscribed("*"); endTime = System.currentTimeMillis(); System.out.println(String.format("LSUB *, folders.length = %d, execTime = %d sec", folders.length, (endTime - startTime) / 1000)); startTime = System.currentTimeMillis(); for (Folder folder : folders) { folder.getMessageCount(); //Folder f = store.getFolder(folder.getFullName()); } endTime = System.currentTimeMillis(); System.out.println(String.format("Folders Loop, folders.length = %d, execTime = %d sec", folders.length, (endTime - startTime) / 1000)); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } finally { try { store.close(); } catch (MessagingException e) { System.err.println(e.getMessage()); } } }
From source file:org.apache.juddi.v3.tck.UDDI_090_Smtp_ExternalTest.java
/** * gets all current messages from the mail server and returns the number * of messages containing the string, messages containing the string are * deleted from the mail server String is the body of each message * * @return number of matching and deleted messages * @param contains a string to search for *//*from w w w . jav a 2s . c o m*/ private static int fetchMail(String contains) { //final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; /* Set the mail properties */ Properties properties = TckPublisher.getProperties(); // Set manual Properties int found = 0; Session session = Session.getDefaultInstance(properties, null); Store store = null; try { store = session.getStore("pop3"); store.connect(properties.getProperty("mail.pop3.host"), Integer.parseInt(properties.getProperty("mail.pop3.port", "110")), properties.getProperty("mail.pop3.username"), properties.getProperty("mail.pop3.password")); /* Mention the folder name which you want to read. */ // inbox = store.getDefaultFolder(); // inbox = inbox.getFolder("INBOX"); Folder inbox = store.getFolder("INBOX"); /* Open the inbox using store. */ inbox.open(Folder.READ_WRITE); Message messages[] = inbox.getMessages(); for (int i = 0; i < messages.length; i++) { MimeMessageParser p = new MimeMessageParser(new MimeMessage(session, messages[i].getInputStream())); Enumeration allHeaders = p.getMimeMessage().getAllHeaders(); while (allHeaders.hasMoreElements()) { Object j = allHeaders.nextElement(); if (j instanceof javax.mail.Header) { javax.mail.Header msg = (javax.mail.Header) j; logger.info("XML as message header is " + msg.getValue()); if (msg.getValue().contains(contains)) { //found it messages[i].setFlag(Flags.Flag.DELETED, true); found++; } } } for (int k = 0; k < p.getAttachmentList().size(); k++) { InputStream is = p.getAttachmentList().get((k)).getInputStream(); QuotedPrintableCodec qp = new QuotedPrintableCodec(); // If "is" is not already buffered, wrap a BufferedInputStream // around it. if (!(is instanceof BufferedInputStream)) { is = new BufferedInputStream(is); } int c; StringBuilder sb = new StringBuilder(); System.out.println("Message : "); while ((c = is.read()) != -1) { sb.append(c); System.out.write(c); } is.close(); String decoded = qp.decode(sb.toString()); logger.info("decode message is " + decoded); if (decoded.contains(contains)) { //found it messages[i].setFlag(Flags.Flag.DELETED, true); found++; } } } inbox.close(true); } catch (Exception ex) { ex.printStackTrace(); } finally { if (store != null) { try { store.close(); } catch (Exception ex) { } } } return found; }