List of usage examples for javax.mail Folder READ_WRITE
int READ_WRITE
To view the source code for javax.mail Folder READ_WRITE.
Click Source Link
From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java
/** * {@inheritDoc}//from w w w . j a v a2s. c o m * * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String) */ @Override public List<Message> read(String folder, boolean onlyUnred, int max) throws MessagingException { Store store = getJavamailStore(); store.connect(); Folder mailFolder = store.getDefaultFolder(); if (StringUtils.isNotEmpty(folder)) { mailFolder = mailFolder.getFolder(folder); } mailFolder.open(Folder.READ_WRITE); Message[] msgsArray = mailFolder.getMessages(); if (max > 0 && msgsArray.length > max) { msgsArray = (Message[]) ArrayUtils.subarray(msgsArray, 0, max); } List<Message> messages = new ArrayList<Message>(Arrays.asList(msgsArray)); mailFolder.close(false); store.close(); return messages; }
From source file:com.cubusmail.server.mail.imap.IMAPMailFolder.java
public Message[] retrieveMessages(MessageListFields sortField, boolean ascending, MessageListFields[] searchFields, String[] searchValues) { Message[] msgs = EMPTY_MESSAGE_ARRAY; if (this.folder != null) { try {/*from w w w .j a v a2s .co m*/ if (!this.folder.isOpen()) { this.folder.open(Folder.READ_WRITE); } long time = System.currentTimeMillis(); log.debug("Start getting messages..."); msgs = folder.getMessages(); log.debug( "Millis for getting " + msgs.length + " messages: " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); FetchProfile fp = MessageUtils.createFetchProfile(false, sortField); log.debug("Start fetching messages..."); folder.fetch(msgs, fp); log.debug( "Millis for fetching " + msgs.length + " Messages: " + (System.currentTimeMillis() - time)); if (searchFields != null && searchFields.length > 0 && searchValues != null && searchValues.length > 0) { log.debug("Start filtering messages..."); SearchTerm term = MessageUtils.createSearchTerm(searchFields, searchValues); msgs = folder.search(term); log.debug("Millis for filtering " + msgs.length + " Messages: " + (System.currentTimeMillis() - time)); } MessageUtils.sortMessages(msgs, sortField, ascending); } catch (MessagingException e) { log.error(e.getMessage(), e); } } return msgs; }
From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java
/** * Opens the IMAP folder, deletes all messages which match the magic subject and * creates a new message with an attachment which contains the object serialized *///from w w w . ja v a2 s . c o m protected static void saveUserPreferencesInIMAP(Log logger, User user, Session session, IMAPStore iStore, String folderName, String subject, Object object) throws MessagingException, IOException, InterruptedException { IMAPFolder folder = (IMAPFolder) iStore.getFolder(folderName); if (folder.exists() || folder.create(IMAPFolder.HOLDS_MESSAGES)) { if (!folder.isOpen()) { folder.open(Folder.READ_WRITE); } // Serialize the object ByteArrayOutputStream fout = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(object); oos.close(); ByteArrayInputStream is = new ByteArrayInputStream(fout.toByteArray()); // Create a new message with an attachment which has the serialized object MimeMessage message = new MimeMessage(session); message.setSubject(subject); Multipart multipart = new MimeMultipart(); MimeBodyPart txtPart = new MimeBodyPart(); txtPart.setContent("This message contains configuration used by Hupa, do not delete it", "text/plain"); multipart.addBodyPart(txtPart); FileItem item = createPreferencesFileItem(is, subject, HUPA_DATA_MIME_TYPE); multipart.addBodyPart(MessageUtils.fileitemToBodypart(item)); message.setContent(multipart); message.saveChanges(); // It seems it's not possible to modify the content of an existing message using the API // So I delete the previous message storing the preferences and I create a new one Message[] msgs = folder.getMessages(); for (Message msg : msgs) { if (subject.equals(msg.getSubject())) { msg.setFlag(Flag.DELETED, true); } } // It is necessary to copy the message before saving it (the same problem in AbstractSendMessageHandler) message = new MimeMessage((MimeMessage) message); message.setFlag(Flag.SEEN, true); folder.appendMessages(new Message[] { message }); folder.close(true); logger.info("Saved preferences " + subject + " in imap folder " + folderName + " for user " + user); } else { logger.error("Unable to save preferences " + subject + " in imap folder " + folderName + " for user " + user); } }
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 www. ja v a 2s .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:com.aurel.track.util.emailHandling.MailReader.java
public synchronized static Message[] readAll(String protocol, String server, int securityConnection, int port, String user, String password, boolean onlyUnreadMessages) { Message[] msgs = null;// ww w. j ava 2s.c o m try { Properties props = System.getProperties(); updateSecurityProps(protocol, server, securityConnection, props); Session session = Session.getDefaultInstance(props, null); if (LOGGER.isDebugEnabled()) { session.setDebug(true); } else { session.setDebug(false); } // instantiate POP3-store and connect to server store = session.getStore(protocol); boolean connected = SyncStore.connect(store, protocol, server, port, user, password); if (!connected) { return msgs; } connPoint = SyncStore.getConnPoint(store, protocol, server, port, user, password); store = connPoint.getStore(); // access default folder folder = store.getDefaultFolder(); // can't find default folder if (folder == null) { throw new Exception("No default folder"); } // messages are always in folder INBOX folder = folder.getFolder("INBOX"); // can't find INBOX if (folder == null) { throw new Exception("No POP3 INBOX"); } // open folder folder.open(Folder.READ_WRITE); // retrieve messages if (onlyUnreadMessages) { FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); msgs = folder.search(ft); } else { msgs = folder.getMessages(); } } catch (Exception ex) { if (LogThrottle.isReady("MailReader1", 240)) { LOGGER.error(ExceptionUtils.getStackTrace(ex)); } } return msgs; }
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); // Get attributes & flags for all messages ///*w ww. j a va 2 s. c o m*/ 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 . j a v a2 s. c om*/ * * @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:ch.entwine.weblounge.bridge.mail.MailAggregator.java
/** * {@inheritDoc}/*www. ja va2 s .c o m*/ * * @see ch.entwine.weblounge.common.scheduler.JobWorker#execute(java.lang.String, * java.util.Dictionary) */ public void execute(String name, Dictionary<String, Serializable> ctx) throws JobException { Site site = (Site) ctx.get(Site.class.getName()); // Make sure the site is ready to accept content if (site.getContentRepository().isReadOnly()) { logger.warn("Unable to publish e-mail messages to site '{}': repository is read only", site); return; } WritableContentRepository repository = (WritableContentRepository) site.getContentRepository(); // Extract the configuration from the job properties String provider = (String) ctx.get(OPT_PROVIDER); Account account = null; try { if (StringUtils.isBlank(provider)) { provider = DEFAULT_PROVIDER; } account = new Account(ctx); } catch (IllegalArgumentException e) { throw new JobException(this, e); } // Connect to the server Properties sessionProperties = new Properties(); Session session = Session.getDefaultInstance(sessionProperties, null); Store store = null; Folder inbox = null; try { // Connect to the server try { store = session.getStore(provider); store.connect(account.getHost(), account.getLogin(), account.getPassword()); } catch (NoSuchProviderException e) { throw new JobException(this, "Unable to connect using unknown e-mail provider '" + provider + "'", e); } catch (MessagingException e) { throw new JobException(this, "Error connecting to " + provider + " account " + account, e); } // Open the account's inbox try { inbox = store.getFolder(INBOX); if (inbox == null) throw new JobException(this, "No inbox found at " + account); inbox.open(Folder.READ_WRITE); } catch (MessagingException e) { throw new JobException(this, "Error connecting to inbox at " + account, e); } // Get the messages from the server try { for (Message message : inbox.getMessages()) { if (!message.isSet(Flag.SEEN)) { try { Page page = aggregate(message, site); message.setFlag(Flag.DELETED, true); repository.put(page, true); logger.info("E-Mail message published at {}", page.getURI()); } catch (Exception e) { logger.info("E-Mail message discarded: {}", e.getMessage()); message.setFlag(Flag.SEEN, true); // TODO: Reply to sender if the "from" field exists } } } } catch (MessagingException e) { throw new JobException(this, "Error loading e-mail messages from inbox", e); } // Close the connection // but don't remove the messages from the server } finally { if (inbox != null) { try { inbox.close(true); } catch (MessagingException e) { throw new JobException(this, "Error closing inbox", e); } } if (store != null) { try { store.close(); } catch (MessagingException e) { throw new JobException(this, "Error closing connection to e-mail server", e); } } } }
From source file:gmailclientfx.controllers.SpamController.java
public void fetchSpam() { ObservableList<MyMessage> data = FXCollections.observableArrayList(); stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId")); stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject")); stupacFrom.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender")); stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived")); spamTable.setItems(data);//from w w w .j a va2 s. co m spamTable.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isPrimaryButtonDown() && event.getClickCount() == 2) { MyMessage selectedMsg = spamTable.getSelectionModel().getSelectedItem(); PregledEmailaHelper.setMsg(selectedMsg); try { Parent root; FXMLLoader loader = new FXMLLoader(); loader.setLocation( getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml")); root = loader.load(); Stage stage = new Stage(); stage.setScene(new Scene(root)); PregledEmailaController pgec = loader.getController(); stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { pgec.bodyWebViewEngine.load(null); System.out.println("Closing form!"); } }); stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - " + PregledEmailaHelper.getMsg().getSender()); stage.show(); } catch (IOException ex) { Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex); } } } }); try { IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(), GmailClient.getAccesToken(), true); Folder spam = null; Folder[] folders = store.getDefaultFolder().list("*"); for (Folder f : folders) { IMAPFolder imapFolder = (IMAPFolder) f; for (String att : imapFolder.getAttributes()) { if ("\\Junk".equals(att)) { spam = f; } } } spam.open(Folder.READ_WRITE); MimeMessage[] seenMessages = (MimeMessage[]) spam .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true)); for (int i = 0; i < seenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "SPAM"); data.add(msg); } MimeMessage[] unseenMessages = (MimeMessage[]) spam .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); for (int i = 0; i < unseenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "SPAM"); data.add(msg); } spam.close(false); store.close(); } catch (Exception ex) { Logger.getLogger(SpamController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:gmailclientfx.controllers.PoslaneController.java
public void fetchPoslane() { ObservableList<MyMessage> data = FXCollections.observableArrayList(); stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId")); stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject")); stupacTo.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender")); stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived")); poslaneTable.setItems(data);//w w w. java 2 s . co m poslaneTable.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isPrimaryButtonDown() && event.getClickCount() == 2) { MyMessage selectedMsg = poslaneTable.getSelectionModel().getSelectedItem(); PregledEmailaHelper.setMsg(selectedMsg); try { Parent root; FXMLLoader loader = new FXMLLoader(); loader.setLocation( getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml")); root = loader.load(); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - " + PregledEmailaHelper.getMsg().getSender()); stage.show(); PregledEmailaController pgec = loader.getController(); stage.setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { pgec.bodyWebViewEngine.load(null); System.out.println("Closing form!"); } }); } catch (IOException ex) { Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex); } } } }); try { IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(), GmailClient.getAccesToken(), true); Folder poslane = null; Folder[] folders = store.getDefaultFolder().list("*"); for (Folder f : folders) { IMAPFolder imapFolder = (IMAPFolder) f; for (String att : imapFolder.getAttributes()) { if ("\\Sent".equals(att)) { poslane = f; } } } poslane.open(Folder.READ_WRITE); MimeMessage[] seenMessages = (MimeMessage[]) poslane .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true)); for (int i = 0; i < seenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "SENT"); data.add(msg); } MimeMessage[] unseenMessages = (MimeMessage[]) poslane .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); for (int i = 0; i < unseenMessages.length; i++) { MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "SENT"); data.add(msg); } poslane.close(false); store.close(); } catch (Exception ex) { Logger.getLogger(PoslaneController.class.getName()).log(Level.SEVERE, null, ex); } }