List of usage examples for javax.mail Store getFolder
public abstract Folder getFolder(URLName url) throws MessagingException;
From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java
/** * Loads email properties, reads email messages, * converts their multipart bodies into string, * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports * <p><b> deletes messages/*from ww w . j av a2 s .c om*/ * @see #readEmail() * @see #convertToXml(HashSet) * @see ru.retbansk.utils.scheduled.ReplyManager * @return HashSet<DayReport> of the Valid Day Reports */ @Override public HashSet<DayReport> readEmail() throws Exception { Properties prop = loadProperties(); String host = prop.getProperty("host"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); path = prop.getProperty("path"); // Get system properties Properties properties = System.getProperties(); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Get a Store object that implements the specified protocol. Store store = session.getStore("pop3"); // Connect to the current host using the specified username and // password. store.connect(host, user, password); // Create a Folder object corresponding to the given name. Folder folder = store.getFolder("inbox"); // Open the Folder. folder.open(Folder.READ_WRITE); HashSet<DayReport> dayReportSet = new HashSet<DayReport>(); try { // Getting messages from the folder Message[] message = folder.getMessages(); // Reversing the order in the array with the use of Set to make the last one final Collections.reverse(Arrays.asList(message)); // Reading messages. String body; for (int i = 0; i < message.length; i++) { DayReport dayReport = null; dayReport = new DayReport(); dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3")); calendar.setTime(message[i].getSentDate()); dayReport.setCalendar(calendar); dayReport.setSubject(message[i].getSubject()); List<TaskReport> reportList = null; //Release the string from email message body body = ""; Object content = message[i].getContent(); if (content instanceof java.lang.String) { body = (String) content; } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } } } //Put the string (body of email message) and get list of valid reports else send error reportList = new ArrayList<TaskReport>(); reportList = giveValidReports(body, message[i].getSentDate()); //Check for valid day report. To be valid it should have size of reportList > 0. if (reportList.size() > 0) { // adding valid ones to Set dayReport.setReportList(reportList); dayReportSet.add(dayReport); } else { // This message doesn't have valid reports. Sending an error reply. logger.info("Invalid Day Report detected. Sending an error reply"); ReplyManager man = new ReplyManagerSimpleImpl(); man.sendError(dayReport); } // Delete message message[i].setFlag(Flags.Flag.DELETED, true); } } finally { // true tells the mail server to expunge deleted messages. folder.close(true); store.close(); } return dayReportSet; }
From source file:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java
@Test public void testOpenImapConnection() throws Exception { Store mailAccount = null; Folder inbox = null;/*from w w w. j a va 2 s. com*/ 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 -- javax.mail.Message[] msgs = inbox.getMessages(); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.FLAGS); inbox.fetch(msgs, profile); MailProcessor processor = new MailProcessor(); MessageListener mailingList = mock(MessageListener.class); when(mailingList.checkSender(anyString())).thenReturn(Boolean.TRUE); when(mailingList.getComponentId()).thenReturn("mailingList38"); MessageEvent event = new MessageEvent(); for (javax.mail.Message message : msgs) { processor.prepareMessage((MimeMessage) message, mailingList, event); } assertThat(event.getMessages(), is(notNullValue())); assertThat(event.getMessages().size(), is(msgs.length)); for (com.silverpeas.mailinglist.service.model.beans.Message message : event.getMessages()) { assertThat(message, is(notNullValue())); assertThat(message.getMessageId(), is(notNullValue())); } } finally { // -- Close down nicely -- if (inbox != null) { inbox.close(false); } if (mailAccount != null) { mailAccount.close(); } } }
From source file:com.intranet.intr.inbox.EmpControllerInbox.java
public int todosCorreosNum(String name) { int num = 0;/*w w w . j a v a2 s .co m*/ Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); try { users u = usuarioService.getByLogin(name); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); Message msg[] = inbox.getMessages(); System.out.println("MAILS: " + msg.length); System.out.println(" " + msg.length); num = msg.length; } catch (Exception ex) { System.out.println(ex.toString()); } return num; }
From source file:com.intranet.intr.inbox.EmpControllerInbox.java
public int numCorreosNOL(String name) { int numMensa = 0; Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); try {/*w w w.ja va2 s . c o m*/ users u = usuarioService.getByLogin(name); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Message msg[] = inbox.search(ft); System.out.println("MAILS: " + msg.length); System.out.println(" " + msg.length); numMensa = msg.length; } catch (Exception ex) { } return numMensa; }
From source file:org.eurekastreams.server.service.email.ImapEmailIngester.java
/** * Ingests email from a mailbox.//from ww w .j a va 2 s . c o m */ public void execute() { // get message store Store store; try { long startTime = System.nanoTime(); store = storeFactory.getStore(); log.debug("Connected to mail store in {}ns", System.nanoTime() - startTime); } catch (MessagingException ex) { log.error("Error getting message store.", ex); return; } try { // get folders Folder inputFolder = store.getFolder(inputFolderName); if (!inputFolder.exists()) { log.error("Input folder {} does not exist.", inputFolderName); return; } Folder successFolder = null; if (StringUtils.isNotBlank(successFolderName)) { successFolder = store.getFolder(successFolderName); if (!successFolder.exists()) { log.error("Success folder {} does not exist.", successFolderName); return; } } Folder discardFolder = null; if (StringUtils.isNotBlank(discardFolderName)) { discardFolder = store.getFolder(discardFolderName); if (!discardFolder.exists()) { log.error("Discard folder {} does not exist.", discardFolderName); return; } } Folder errorFolder = null; if (StringUtils.isNotBlank(errorFolderName)) { errorFolder = store.getFolder(errorFolderName); if (!errorFolder.exists()) { log.error("Error folder {} does not exist.", errorFolderName); return; } } inputFolder.open(Folder.READ_WRITE); // fetch messages // Note: Not preloading CONTENT_INFO. For some reason, preloading the content info (IMAP BODYSTRUCTURE) // causes the call to getContent to return empty. (As if there was a bug where getContent saw the cached // body structure and thought that the content itself was cached, but I'd think a bug like that would have // been found by many people and fixed long ago, so I'm assuming it's something else.) FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); Message[] msgs = inputFolder.getMessages(); inputFolder.fetch(msgs, fp); log.debug("About to process {} messages", msgs.length); // process each message if (msgs.length > 0) { List<Message> successMessages = new ArrayList<Message>(); List<Message> errorMessages = new ArrayList<Message>(); List<Message> discardMessages = new ArrayList<Message>(); List<Message> responseMessages = new ArrayList<Message>(); for (int i = 0; i < msgs.length; i++) { Message message = msgs[i]; try { boolean processed = messageProcessor.execute(message, responseMessages); (processed ? successMessages : discardMessages).add(message); } catch (Exception ex) { log.error("Failed to process email message.", ex); errorMessages.add(message); } } // send response messages for (Message responseMessage : responseMessages) { emailerFactory.sendMail(responseMessage); } // move and purge messages if (successFolder != null && !successMessages.isEmpty()) { inputFolder.copyMessages(successMessages.toArray(new Message[successMessages.size()]), successFolder); } if (discardFolder != null && !discardMessages.isEmpty()) { inputFolder.copyMessages(discardMessages.toArray(new Message[discardMessages.size()]), discardFolder); } if (errorFolder != null && !errorMessages.isEmpty()) { inputFolder.copyMessages(errorMessages.toArray(new Message[errorMessages.size()]), errorFolder); } for (int i = 0; i < msgs.length; i++) { msgs[i].setFlag(Flag.DELETED, true); } log.info("{} messages processed: {} successful, {} discarded, {} failed.", new Object[] { msgs.length, successMessages.size(), discardMessages.size(), errorMessages.size() }); } // close folder inputFolder.close(true); } catch (MessagingException ex) { log.error("Error ingesting email.", ex); } catch (Exception ex) { log.error("Error ingesting email.", ex); } finally { // close store try { store.close(); } catch (MessagingException ex) { log.error("Error closing message store.", ex); } } }
From source file:org.apache.syncope.core.notification.NotificationTest.java
private boolean verifyMail(final String sender, final String subject) throws Exception { LOG.info("Waiting for notification to be sent..."); try {// ww w. ja v a2s .c om Thread.sleep(1000); } catch (InterruptedException e) { } boolean found = false; Session session = Session.getDefaultInstance(System.getProperties()); Store store = session.getStore("pop3"); store.connect(pop3Host, pop3Port, 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(); return found; }
From source file:com.intranet.intr.inbox.EmpControllerInbox.java
@RequestMapping(value = "/EajaxtestNoL", method = RequestMethod.GET) public @ResponseBody String ajaxtestNoL(Principal principal) { String name = principal.getName(); String result = ""; try {/*from ww w . ja va 2 s . c o m*/ users u = usuarioService.getByLogin(name); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Calendar fecha3 = Calendar.getInstance(); fecha3.roll(Calendar.MONTH, false); Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime())); //Message msg[] = inbox.search(ft); System.out.println("MAILS: " + msg.length); for (Message message : msg) { try { /*System.out.println("DATE: "+message.getSentDate().toString()); System.out.println("FROM: "+message.getFrom()[0].toString()); System.out.println("SUBJECT: "+message.getSubject().toString()); System.out.println("CONTENT: "+message.getContent().toString()); System.out.println("******************************************"); */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>" + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString() + "</span>" + message.getSubject().toString() + "</span>" + "</span>" + "</a>" + "</li> "; } catch (Exception e) { // TODO Auto-generated catch block System.out.println("No Information"); } } } catch (Exception ex) { } return result; }
From source file:com.intranet.intr.inbox.EmpControllerInbox.java
public correoNoLeidos ltaRecibidos2(String name, int num) { correoNoLeidos lta = new correoNoLeidos(); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); try {/*from www . ja v a 2 s .co m*/ users u = usuarioService.getByLogin(name); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); Calendar fecha3 = Calendar.getInstance(); fecha3.roll(Calendar.MONTH, false); Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime())); //Message msg[] = inbox.getMessages(); System.out.println("MAILS: " + msg.length); for (Message message : msg) { try { if (num == message.getMessageNumber()) { //message.setFlag(Flags.Flag.SEEN, true); lta.setNum(message.getMessageNumber()); lta.setFecha(message.getSentDate().toString()); lta.setDe(message.getFrom()[0].toString()); lta.setAsunto(message.getSubject().toString()); correoNoLeidos co = new correoNoLeidos(); List<String> arc = new ArrayList<String>(); List<String> rar = new ArrayList<String>(); correoNoLeidos cc = analizaParteDeMensaje2(co, arc, rar, message); lta.setImagenes(cc.getImagenes()); lta.setRar(cc.getRar()); lta.setContenido(cc.getContenido()); String cont = ""; String contenido = ""; //lta.setContenido(analizaParteDeMensaje2(message)); } } catch (Exception e) { System.out.println("No Information"); } } } catch (MessagingException e) { System.out.println(e.toString()); } return lta; }
From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java
private void doReceiveMessages() throws Exception { log.debug("Checking mail "); String host = Turbine.getConfiguration().getString("mail.pop3.host"); String username = Turbine.getConfiguration().getString("mail.pop3.user"); String password = Turbine.getConfiguration().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);//from w ww . j av a2 s. com // 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); for (int i = 0; i < messages.length; i++) { log.debug("Retrieving message " + i); // Process each message // InboxEvent entry = new InboxEvent(); Address fromAddress = new InternetAddress(); String from = new String(); String name = new String(); String email = new String(); String replyTo = new String(); String subject = new String(); String content = new String(); Date sentDate = new Date(); int emailformat = 10; Message m = messages[i]; // and now, handle the content Object o = m.getContent(); // find content type if (m.isMimeType("text/plain")) { content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>"; emailformat = 10; } else if (m.isMimeType("text/html")) { content = (String) o; emailformat = 20; } else if (m.isMimeType("text/*")) { content = (String) o; emailformat = 30; } else if (m.isMimeType("multipart/alternative")) { try { content = handleAlternative(o, content); emailformat = 20; } catch (Exception ex) { content = "Problem with the message format. Messssage has left on the email server."; emailformat = 50; log.error(ex.getMessage(), ex); } } else if (m.isMimeType("multipart/*")) { try { content = handleMulitipart(o, content, entry); emailformat = 40; } catch (Exception ex) { content = "Problem with the message format. Messssage has left on the email server."; emailformat = 50; log.error(ex.getMessage(), ex); } } else { content = "Problem with the message format. Messssage has left on the email server."; emailformat = 50; log.debug("Could not handle properly"); } email = ((InternetAddress) m.getFrom()[0]).getAddress(); name = ((InternetAddress) m.getFrom()[0]).getPersonal(); replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress(); sentDate = m.getSentDate(); subject = m.getSubject(); log.debug("Got message " + email + " " + name + " " + subject + " " + content); Criteria contcrit = new Criteria(); contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL); if (ContactPeer.doSelect(contcrit).size() > 0) { log.debug("From known contact"); Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0); entry.setCustomerId(myContact.getCustomerId()); entry.setContactId(myContact.getContactId()); } else { // find if customer exists Criteria criteria = new Criteria(); criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL); if (CustomerPeer.doSelect(criteria).size() > 0) { log.debug("From known customer"); Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0); entry.setCustomerId(myDistrib.getCustomerId()); } } entry.setInboxEventCode(getTempCode()); entry.setEventType(10); entry.setEventChannel(10); entry.setEmailFormat(emailformat); entry.setSubject(subject); entry.setSenderEmail(email); entry.setSenderName(name); entry.setSenderReplyTo(replyTo); entry.setSentTime(sentDate); entry.setBody(content); entry.setIssuedDate(new Date()); entry.setCreatedBy("system"); entry.setCreated(new Date()); entry.setModifiedBy("system"); entry.setModified(new Date()); Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME); boolean success = false; try { entry.save(conn); entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId())); entry.save(conn); Transaction.commit(conn); success = true; } finally { log.debug("Succcessfully stored in db: " + success); if (!success) Transaction.safeRollback(conn); } if (emailformat != 50) { m.setFlag(Flags.Flag.DELETED, true); } } // Close pop3 connection folder.close(true); store.close(); }
From source file:com.intranet.intr.inbox.SupControllerInbox.java
@RequestMapping(value = "/ajaxtestNoL", method = RequestMethod.GET) public @ResponseBody String ajaxtestNoL(Principal principal) { String name = principal.getName(); String result = ""; try {/*from w ww. ja v a 2s. com*/ users u = usuarioService.getByLogin(name); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Calendar fecha3 = Calendar.getInstance(); fecha3.roll(Calendar.MONTH, false); Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime())); //Message msg[] = inbox.search(ft); System.out.println("MAILS: " + msg.length); for (Message message : msg) { try { /*System.out.println("DATE: "+message.getSentDate().toString()); System.out.println("FROM: "+message.getFrom()[0].toString()); System.out.println("SUBJECT: "+message.getSubject().toString()); System.out.println("CONTENT: "+message.getContent().toString()); System.out.println("******************************************"); */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>" + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString() + "</span>" + message.getSubject().toString() + "</span>" + "</span>" + "</a>" + "</li> "; } catch (Exception e) { // TODO Auto-generated catch block System.out.println("No Information"); } } } catch (Exception ex) { } return result; }