List of usage examples for javax.mail Store getFolder
public abstract Folder getFolder(URLName url) throws MessagingException;
From source file:com.ikon.util.MailUtils.java
/** * Test IMAP connection//from ww w .jav a 2s .c o 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.crawlersick.nettool.GetattchmentFromMail1.java
public boolean fetchmailforattch() throws IOException, MessagingException { boolean fetchtest = false; Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); try {/*from www. ja v a 2s . c o m*/ Session session = Session.getInstance(props, null); Store store = session.getStore(); store.connect(IMapHost, MailId, MailPassword); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); totalmailcount = inbox.getMessageCount(); Message msg = null; for (int i = totalmailcount; i > 0; i--) { fromadd = ""; msg = inbox.getMessage(i); Address[] in = msg.getFrom(); for (Address address : in) { fromadd = address.toString() + fromadd; //System.out.println("FROM:" + address.toString()); } if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches( "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice")) break; } if (fromadd.equals("'")) { log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId); return fetchtest; } // Multipart mp = (Multipart) msg.getContent(); // BodyPart bp = mp.getBodyPart(0); sentdate = msg.getSentDate().toString(); subject = msg.getSubject(); Content = msg.getContent().toString(); log.log(Level.INFO, Content); log.log(Level.INFO, sentdate); localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data..."); LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent); Multipart multipart = (Multipart) msg.getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) { continue; // dealing with attachments only } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); InputStream is = bodyPart.getInputStream(); //validvgbinary = IOUtils.toByteArray(is); int nRead; byte[] data = new byte[5000000]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); validvgbinary = buffer.toByteArray(); break; } fetchtest = true; } catch (Exception mex) { mex.printStackTrace(); } return fetchtest; }
From source file:org.usergrid.rest.management.RegistrationIT.java
private Message[] getMessages(String host, String user, String password) throws MessagingException, IOException { Session session = Session.getDefaultInstance(new Properties()); Store store = session.getStore("imap"); store.connect(host, user, password); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY);// w w w .java 2 s .c o m Message[] msgs = folder.getMessages(); for (Message m : msgs) { logger.info("Subject: " + m.getSubject()); logger.info("Body content 0 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(0).getContent()); logger.info("Body content 1 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(1).getContent()); } return msgs; }
From source file:org.apache.usergrid.rest.management.RegistrationIT.java
private Message[] getMessages(String host, String user, String password) throws MessagingException, IOException { Session session = Session.getDefaultInstance(new Properties()); Store store = session.getStore("imap"); store.connect(host, user, password); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY);/*from ww w. ja v a 2s.c o m*/ Message[] msgs = folder.getMessages(); for (Message m : msgs) { logger.info("Subject: " + m.getSubject()); logger.info("Body content 0 " + ((MimeMultipart) m.getContent()).getBodyPart(0).getContent()); logger.info("Body content 1 " + ((MimeMultipart) m.getContent()).getBodyPart(1).getContent()); } return msgs; }
From source file:org.campware.dream.modules.scheduledjobs.Pop3Job.java
private void doReceiveMessages() throws Exception { String host = TurbineResources.getString("mail.pop3.host"); String username = TurbineResources.getString("mail.pop3.user"); String password = TurbineResources.getString("mail.pop3.password"); // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); // Get the store Store store = session.getStore("pop3"); // Connect to store store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); // Open read-only folder.open(Folder.READ_WRITE);/* w ww . j ava 2 s. c om*/ // Get attributes & flags for all messages // Message[] messages = folder.getMessages(); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(messages, fp); // Process each message // Address fromAddress = new InternetAddress(); String from = new String(); String name = new String(); String email = new String(); String subject = new String(); String content = new String(); for (int i = 0; i < messages.length; i++) { email = ((InternetAddress) messages[i].getFrom()[0]).getAddress(); name = ((InternetAddress) messages[i].getFrom()[0]).getPersonal(); subject = messages[i].getSubject(); content = messages[i].getContent().toString(); DinboxEvent entry = new DinboxEvent(); Criteria criteria = new Criteria(); criteria.add(DistributorPeer.EMAIL, (Object) email, Criteria.EQUAL); if (DistributorPeer.doSelect(criteria).size() > 0) { Distributor myDistrib = (Distributor) DistributorPeer.doSelect(criteria).get(0); entry.setDistributorId(myDistrib.getDistributorId()); } else { if (name != null) { entry.setBody("From: " + name + " " + email + "\n\n" + content); } else { entry.setBody("From: " + email + "\n\n" + content); } } entry.setDinboxEventCode(getTempCode()); entry.setEventType(10); entry.setEventChannel(10); entry.setSubject(subject); entry.setIssuedDate(new Date()); entry.setCreatedBy("scheduler"); entry.setCreated(new Date()); entry.setModifiedBy("scheduler"); entry.setModified(new Date()); Connection conn = Transaction.begin(DinboxEventPeer.DATABASE_NAME); boolean success = false; try { entry.save(conn); entry.setDinboxEventCode(getRowCode("IE", entry.getDinboxEventId())); entry.save(conn); Transaction.commit(conn); success = true; } finally { if (!success) Transaction.safeRollback(conn); } messages[i].setFlag(Flags.Flag.DELETED, true); } // Close connection folder.close(true); store.close(); }
From source file:org.syncope.core.notification.NotificationTest.java
private boolean verifyMail(final String sender, final String subject) { LOG.info("Waiting for notification to be sent..."); try {//from www . j av a2 s .com Thread.sleep(10000); } catch (InterruptedException e) { } boolean found = false; try { Session session = Session.getDefaultInstance(System.getProperties()); Store store = session.getStore("pop3"); store.connect(pop3Host, mailAddress, mailPassword); Folder inbox = store.getFolder("INBOX"); assertNotNull(inbox); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); for (int i = 0; i < messages.length; i++) { if (sender.equals(messages[i].getFrom()[0].toString()) && subject.equals(messages[i].getSubject())) { found = true; messages[i].setFlag(Flag.DELETED, true); } } inbox.close(true); store.close(); } catch (Throwable t) { LOG.error("Unexpected exception", t); fail("Unexpected exception while fetching e-mail"); } return found; }
From source file:com.openkm.util.MailUtils.java
/** * Import messages/*from w ww. j a va2s.com*/ * http://www.jguru.com/faq/view.jsp?EID=26898 * * == Using Unique Identifier (UIDL) == * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email, * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't * receive it; otherwise receive it. * * == Different property of UIDL in POP3 and IMAP4 == * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is * no longer exist on the POP3 server. * * == Remarks == * You should create different local uidl list for different email account, because the uidl is only * unique for the same account. */ public static String importMessages(String token, MailAccount ma) throws PathNotFoundException, ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException { log.debug("importMessages({}, {})", new Object[] { token, ma }); Session session = Session.getDefaultInstance(getProperties()); String exceptionMessage = null; try { // Open connection Store store = session.getStore(ma.getMailProtocol()); store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword()); Folder folder = store.getFolder(ma.getMailFolder()); folder.open(Folder.READ_WRITE); Message messages[] = null; if (folder instanceof IMAPFolder) { // IMAP folder UIDs begins at 1 and are supposed to be sequential. // Each folder has its own UIDs sequence, not is a global one. messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID); } else { messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; log.info("======= ======= {} ======= =======", i); log.info("Subject: {}", msg.getSubject()); log.info("From: {}", msg.getFrom()); log.info("Received: {}", msg.getReceivedDate()); log.info("Sent: {}", msg.getSentDate()); com.openkm.bean.Mail mail = messageToMail(msg); if (ma.getMailFilters().isEmpty()) { log.debug("Import in compatibility mode"); String mailPath = getUserMailPath(ma.getUser()); importMail(token, mailPath, true, folder, msg, ma, mail); } else { for (MailFilter mf : ma.getMailFilters()) { log.debug("MailFilter: {}", mf); if (checkRules(mail, mf.getFilterRules())) { String mailPath = mf.getPath(); importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail); } } } // Set message as seen if (ma.isMailMarkSeen()) { msg.setFlag(Flags.Flag.SEEN, true); } else { msg.setFlag(Flags.Flag.SEEN, false); } // Delete read mail if requested if (ma.isMailMarkDeleted()) { msg.setFlag(Flags.Flag.DELETED, true); } // Set lastUid if (folder instanceof IMAPFolder) { long msgUid = ((IMAPFolder) folder).getUID(msg); log.info("Message UID: {}", msgUid); ma.setMailLastUid(msgUid); MailAccountDAO.update(ma); } } // Close connection log.debug("Expunge: {}", ma.isMailMarkDeleted()); folder.close(ma.isMailMarkDeleted()); store.close(); } catch (NoSuchProviderException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (MessagingException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } catch (IOException e) { log.error(e.getMessage(), e); exceptionMessage = e.getMessage(); } log.debug("importMessages: {}", exceptionMessage); return exceptionMessage; }
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. java 2 s . c o m * @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.alfresco.repo.imap.RemoteLoadTester.java
public void testMailbox() { logger.info("Getting folder..."); long t = System.currentTimeMillis(); // Create empty properties Properties props = new Properties(); props.setProperty("mail.imap.partialfetch", "false"); // Get session Session session = Session.getDefaultInstance(props, null); Store store = null; Folder folder = null;/*from w w w . j a v a 2 s. com*/ try { // Get the store store = session.getStore("imap"); store.connect(REMOTE_HOST, USER_NAME, USER_PASSWORD); // Get folder folder = store.getFolder(TEST_FOLDER_NAME); folder.open(Folder.READ_ONLY); // Get directory Message message[] = folder.getMessages(); for (int i = 0, n = message.length; i < n; i++) { message[i].getAllHeaders(); Address[] from = message[i].getFrom(); System.out.print(i + ": "); if (from != null) { System.out.print(message[i].getFrom()[0] + "\t"); } System.out.println(message[i].getSubject()); Object content = message[i].getContent(); if (content instanceof MimeMultipart) { for (int j = 0, m = ((MimeMultipart) content).getCount(); j < m; j++) { BodyPart part = ((MimeMultipart) content).getBodyPart(j); Object partContent = part.getContent(); if (partContent instanceof String) { String body = (String) partContent; } else if (partContent instanceof FilterInputStream) { FilterInputStream fis = (FilterInputStream) partContent; BufferedInputStream bis = new BufferedInputStream(fis); /* while (bis.available() > 0) { bis.read(); }*/ byte[] bytes = new byte[524288]; while (bis.read(bytes) != -1) { } bis.close(); fis.close(); } } } int nn = 0; } t = System.currentTimeMillis() - t; logger.info("Time: " + t + " ms (" + t / 1000 + " s)"); logger.info("Length: " + message.length); } catch (Exception e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } finally { // Close connection try { if (folder != null) { folder.close(false); } } catch (MessagingException e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } try { if (store != null) { store.close(); } } catch (MessagingException e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } } }
From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java
/** * Returns new messages and fetches details for each message. *//*from w ww.j a v a 2 s . c om*/ @Transactional(readOnly = false) public ResultClass<Boolean> downloadEmails() { ResultClass<Boolean> result = new ResultClass<>(); Properties properties = getServerProperties(protocol, host, port); Session session = Session.getDefaultInstance(properties); try { // connects to the message store Store store = session.getStore(protocol); store.connect(userName, password); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; String[] idHeaders = msg.getHeader("MESSAGE-ID"); if (idHeaders != null && idHeaders.length > 0) { MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]); if (exists == null) { MessageBox messageBox = new MessageBox(); messageBox.setSubject(msg.getSubject()); messageBox.setCode(idHeaders[0]); Address[] fromAddresses = msg.getFrom(); String from = InternetAddress.toString(fromAddresses); if (from.startsWith("=?")) { from = MimeUtility.decodeWord(from); } messageBox.setFrom(from); String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO)); if (to.startsWith("=?")) { to = MimeUtility.decodeWord(to); } messageBox.setTo(to); String[] replyHeaders = msg.getHeader("References"); if (replyHeaders != null && replyHeaders.length > 0) { StringTokenizer tokens = new StringTokenizer(replyHeaders[0]); MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken()); if (parent != null) parent.addReply(messageBox); } result = parseSubjectAndCreate(messageBox, msg); } } } folderInbox.close(false); store.close(); return result; } catch (NoSuchProviderException ex) { logger.error("No provider for protocol: " + protocol); ex.printStackTrace(); } catch (MessagingException ex) { logger.error("Could not connect to the message store"); ex.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } result.setSingleElement(false); return result; }