List of usage examples for javax.mail Folder getMessages
public synchronized Message[] getMessages() throws MessagingException
From source file:org.apache.syncope.core.logic.NotificationTest.java
private boolean verifyMail(final String sender, final String subject) throws Exception { LOG.info("Waiting for notification to be sent..."); try {/* w w w . j a v a 2 s .c om*/ Thread.sleep(1000); } catch (InterruptedException e) { } boolean found = false; Session session = Session.getDefaultInstance(System.getProperties()); Store store = session.getStore("pop3"); store.connect(POP3_HOST, POP3_PORT, MAIL_ADDRESS, MAIL_PASSWORD); 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:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * Retrieve HTML representation of mail message * /*from ww w . j av a 2s .c o m*/ * @param mid * @return */ public String getHTMLMessage(int mid) { String html = null; if (store == null) return html; try { /* * Connect to IMAP store */ store.connect(); /* * Retrieve & open INBOX folder */ Folder folder = store.getFolder(ImapConstants.INBOX); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); Message m = null; for (int i = 0; i < messages.length; i++) { if (i == mid) m = messages[i]; } if (m == null) return html; html = mail2HTML(m); folder.close(false); store.close(); } catch (Exception e) { e.printStackTrace(); } return html; }
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 w w .j av a 2 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:org.opennms.javamail.JavaReadMailer.java
/** * <p>retrieveMessages</p>//from w w w . ja v a2s .com * * @return a {@link java.util.List} object. * @throws org.opennms.javamail.JavaMailerException if any. */ public List<Message> retrieveMessages() throws JavaMailerException { Message[] msgs; Folder mailFolder = null; try { m_store = m_session.getStore(m_config.getReadmailHost().getReadmailProtocol().getTransport()); m_store.connect(m_config.getReadmailHost().getHost(), (int) m_config.getReadmailHost().getPort(), m_config.getUserAuth().getUserName(), m_config.getUserAuth().getPassword()); mailFolder = m_store.getFolder(m_config.getMailFolder()); mailFolder.open(Folder.READ_WRITE); msgs = mailFolder.getMessages(); } catch (NoSuchProviderException e) { throw new JavaMailerException( "No provider matching:" + m_config.getReadmailHost().getReadmailProtocol().getTransport() + " from config:" + m_config.getName(), e); } catch (MessagingException e) { throw new JavaMailerException("Problem reading messages from configured mail store", e); } return new ArrayList<Message>(Arrays.asList(msgs)); }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * Retrieve attachment from message id// w w w .j ava2 s .co m * * @param mid * @return */ public FileUtil getAttachment(int mid) { FileUtil file = null; if (store == null) return file; try { /* * Connect to IMAP store */ store.connect(); /* * Retrieve & open INBOX folder */ Folder folder = store.getFolder(ImapConstants.INBOX); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); Message m = null; /* * Message message = folder.getMessage(mid); * * the method 'getMessage' always returns an * index out of bound error, so we have to * introduce the hack below */ for (int i = 0; i < messages.length; i++) { if (i == mid) m = messages[i]; } if (m == null) return file; Object content = m.getContent(); if (content instanceof Multipart) { file = handleMultipart((Multipart) content, true); } else { file = handlePart(m, true); } folder.close(false); store.close(); } catch (Exception e) { e.printStackTrace(); } return file; }
From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
public Message[] getPOPMessages(Folder folder, int retrievemails) throws Exception { // Get messages .. try {// w w w.ja v a2 s.c o m int unreadMsgs = folder.getUnreadMessageCount(); Message msgsAll[] = folder.getMessages(); int msgCount = msgsAll.length; if (retrievemails == 1) { Message msgsUnread[] = folder.getMessages(msgCount - unreadMsgs + 1, msgCount); return (msgsUnread); } else { return (msgsAll); } } catch (Exception e) { return null; } }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * Retrieve mail messages in a JSON representation * /* w w w.j a va 2 s . c o m*/ * @return */ public JSONArray getJMessages() { JSONArray jMessages = new JSONArray(); if (store == null) return jMessages; try { /* * Connect to IMAP store */ store.connect(); /* * Retrieve & open INBOX folder */ Folder folder = store.getFolder(ImapConstants.INBOX); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { Message m = messages[i]; JSONObject jMessage = new JSONObject(); jMessage.put(ImapConstants.J_KEY, ""); // introduced to be compatible with posted emails jMessage.put(ImapConstants.J_ID, i); // message identifier to retrieve from external server jMessage.put(ImapConstants.J_SUBJECT, m.getSubject()); jMessage.put(ImapConstants.J_DATE, m.getSentDate()); String from = ""; Address[] addresses = m.getFrom(); for (Address address : addresses) { InternetAddress internetAddress = (InternetAddress) address; from = internetAddress.getPersonal(); } jMessage.put(ImapConstants.J_FROM, from); FileUtil attachment = getAttachment(m); if (attachment == null) { jMessage.put(ImapConstants.J_ATTACHMENT, false); } else { jMessage.put(ImapConstants.J_ATTACHMENT, true); } jMessages.put(jMessages.length(), jMessage); } folder.close(false); store.close(); } catch (Exception e) { e.printStackTrace(); } finally { } return jMessages; }
From source file:org.xwiki.contrib.mail.internal.DefaultMailReader.java
/** * {@inheritDoc}/*from www .java 2 s. c om*/ * * @throws MessagingException * @throws * @throws Exception * @see org.xwiki.contrib.mail.IMailReader#read(java.lang.String, int, java.lang.String, java.lang.String, * java.lang.String, java.lang.String, boolean, int) */ @Override public List<Message> read(final String folder, final boolean onlyUnread, final int max) throws MessagingException { assert (getMailSource() != null); assert (getMailSource().getHostname() != null); store = null; List<Message> messages = new ArrayList<Message>(); boolean isGmail = getMailSource().getHostname() != null && getMailSource().getHostname().endsWith(".gmail.com"); logger.info("Trying to retrieve mails from server " + getMailSource().getHostname()); this.session = createSession(getMailSource().getProtocol(), getMailSource().getAdditionalProperties(), isGmail, getMailSource().isAutoTrustSSLCertificates()); // Get a Store object store = session.getStore(); // Connect to the mail account store.connect(getMailSource().getHostname(), getMailSource().getPort(), getMailSource().getUsername(), getMailSource().getPassword()); Folder fldr; // Specifically for GMAIL ... if (isGmail) { fldr = store.getDefaultFolder(); } fldr = store.getFolder(folder); fldr.open(Folder.READ_WRITE); Message[] msgsArray; // Searches for mails not already read if (onlyUnread) { FlagTerm searchterms = new FlagTerm(new Flags(Flags.Flag.SEEN), false); msgsArray = fldr.search(searchterms); } else { msgsArray = fldr.getMessages(); } if (max > 0 && msgsArray.length > max) { msgsArray = (Message[]) ArrayUtils.subarray(msgsArray, 0, max); } messages = new ArrayList<Message>(Arrays.asList(msgsArray)); logger.info("Found " + messages.size() + " messages"); // Note: we leave the Store opened to allow reading returned Messages return messages; }
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 w w . j a va 2s.co m 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.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; }/*from w ww . ja va 2s . 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; }