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.springframework.integration.mail.AbstractMailReceiver.java
@Override protected void onInit() throws Exception { super.onInit(); this.folderOpenMode = Folder.READ_WRITE; this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory()); this.initialized = true; }
From source file:com.stimulus.archiva.incoming.IAPRunnable.java
public void establishConnection(String protocol, String server, int port, String username, String password, Properties props) throws ArchivaException { logger.debug("establishConnection() protocol='" + protocol + "',server='" + server + "',port='" + port + "',username='" + username + "',password='********'}"); Session session = Session.getInstance(props, null); if (System.getProperty("mailarchiva.mail.debug") != null) session.setDebug(true);//from w w w .ja v a 2 s .c o m try { logger.debug("iap connect " + props); store = session.getStore(protocol); } catch (Throwable nspe) { logger.error("failed to retrieve iap store object:" + nspe, nspe); return; } if (logger.isDebugEnabled()) { logger.debug("mailbox connection properties " + props); } try { store.connect(server, port, username, password); } catch (AuthenticationFailedException e) { logger.error("cannot connect to mail server. authentication failed {" + props + "}"); throw new ArchivaException("unable to connect to mail server. could not authenticate. {" + props + "}", e, logger); } catch (IllegalStateException ise) { throw new ArchivaException("attempt to connect mail server when it already connected. {" + props + "}", ise, logger); } catch (MessagingException me) { if (me.getMessage().contains("sun.security.validator.ValidatorException")) { throw new ArchivaException( "failed to authenticate TLS certificate. You must install the mail server's certificate as per the administration guide.", me, logger); } else if (connection.getConnectionMode() == MailboxConnections.ConnectionMode.FALLBACK && me.getMessage().contains("javax.net.ssl.SSLHandshakeException")) { logger.debug("cannot establish SSL handshake with mail server. falling back to insecure. {" + props + "}"); connection.setConnectionMode(MailboxConnections.ConnectionMode.INSECURE); } else throw new ArchivaException( "failed to connect to mail server. " + me.getMessage() + ". {" + props + "}", me, logger); } catch (Throwable e) { throw new ArchivaException("unable to connect to mail server:" + e.getMessage(), e, logger); } try { inboxFolder = store.getDefaultFolder(); } catch (Throwable e) { throw new ArchivaException("unable to get default folder. ", e, logger); } if (inboxFolder == null) { throw new ArchivaException("there was no default POP inbox folder found.", logger); } try { inboxFolder = inboxFolder.getFolder("INBOX"); if (inboxFolder == null) { throw new ArchivaException("the inbox folder does not exist.", logger); } } catch (Throwable e) { throw new ArchivaException("unable to get INBOX folder. ", e, logger); } try { inboxFolder.open(Folder.READ_WRITE); } catch (Throwable e) { throw new ArchivaException("unable to open folder. ", e, logger); } return; }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Mark a given {@link GmailMessage} as read. * * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()} * @throws GmailException if unable to mark {@link GmailMessage} as read *//*from w w w . j a v a2s . c o m*/ public void markAsRead(int messageNumber) { if (messageNumber <= 0) { throw new GmailException("ImapGmailClient invalid " + "GmailMessage number"); } Folder folder = null; try { final Store store = openGmailStore(); folder = getFolder(this.srcFolder, store); folder.open(Folder.READ_WRITE); Message message = folder.getMessage(messageNumber); if (!message.isSet(Flags.Flag.SEEN)) { message.setFlag(Flags.Flag.SEEN, true); } } catch (Exception e) { throw new GmailException("ImapGmailClient failed marking" + " GmailMessage as read : " + messageNumber, e); } finally { closeFolder(folder); } }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Mark all {@link GmailMessage}(s) as read in a folder. * * @throws GmailException if unable to mark all {@link GmailMessage} as read *//*from w ww . j a v a 2 s .c o m*/ public void markAllAsRead() { Folder folder = null; try { final Store store = openGmailStore(); folder = getFolder(this.srcFolder, store); folder.open(Folder.READ_WRITE); for (final Message message : folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) { message.setFlag(Flags.Flag.SEEN, true); } } catch (Exception e) { throw new GmailException("ImapGmailClient failed marking" + " all GmailMessage as read", e); } finally { closeFolder(folder); } }
From source file:org.pentaho.di.job.entries.getpop.MailConnection.java
/** * Open the folder.//from w w w. j a v a 2s .c o m * * @param foldername * the name of the folder to open * @param defaultFolder * true to open the default folder (INBOX) * @param write * open the folder in write mode * @throws KettleException * if something went wrong. */ public void openFolder(String foldername, boolean defaultFolder, boolean write) throws KettleException { this.write = write; try { if (getFolder() != null) { // A folder is already opened // before make sure to close it closeFolder(true); } if (defaultFolder) { if (protocol == MailConnectionMeta.PROTOCOL_MBOX) { this.folder = this.store.getDefaultFolder(); } else { // get the default folder this.folder = getRecursiveFolder(MailConnectionMeta.INBOX_FOLDER); } if (this.folder == null) { throw new KettleException( BaseMessages.getString(PKG, "JobGetMailsFromPOP.InvalidDefaultFolder.Label")); } if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) { throw new KettleException( BaseMessages.getString(PKG, "MailConnection.DefaultFolderCanNotHoldMessage")); } } else { // Open specified Folder (for IMAP/MBOX) if (this.protocol == MailConnectionMeta.PROTOCOL_IMAP || this.protocol == MailConnectionMeta.PROTOCOL_MBOX) { this.folder = getRecursiveFolder(foldername); } if (this.folder == null || !this.folder.exists()) { throw new KettleException( BaseMessages.getString(PKG, "JobGetMailsFromPOP.InvalidFolder.Label")); } } if (this.write) { if (log.isDebug()) { log.logDebug(BaseMessages.getString(PKG, "MailConnection.OpeningFolderInWriteMode.Label", getFolderName())); } this.folder.open(Folder.READ_WRITE); } else { if (log.isDebug()) { log.logDebug(BaseMessages.getString(PKG, "MailConnection.OpeningFolderInReadMode.Label", getFolderName())); } this.folder.open(Folder.READ_ONLY); } if (log.isDetailed()) { log.logDetailed( BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Label", getFolderName())); } if (log.isDebug()) { // display some infos on folder //CHECKSTYLE:LineLength:OFF log.logDebug(BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Name", getFolderName())); log.logDebug(BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.FullName", this.folder.getFullName())); log.logDebug(BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Url", this.folder.getURLName().toString())); log.logDebug(BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Subscribed", "" + this.folder.isSubscribed())); } } catch (Exception e) { throw new KettleException( defaultFolder ? BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.OpeningDefaultFolder") : BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.OpeningFolder", foldername), e); } }
From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java
/** * A method that executes the reading of data from the email account to the * RBNB server after all configuration of settings, connections to hosts, * and thread initiatizing occurs. This method contains the detailed code * for reading the data and interpreting the data files. *//*w w w. ja va 2 s . c om*/ protected boolean execute() { logger.debug("StorXDispatcher.execute() called."); boolean failed = true; // indicates overall success of execute() boolean messageProcessed = false; // indicates per message success // declare the account properties that will be pulled from the // email.account.properties.xml file String accountName = ""; String server = ""; String username = ""; String password = ""; String protocol = ""; String dataMailbox = ""; String processedMailbox = ""; String prefetch = ""; // fetch data from each sensor in the account list List accountList = this.xmlConfiguration.getList("account.accountName"); for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) { int aIndex = accountList.indexOf(aIterator.next()); // populate the email connection variables from the xml properties // file accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName"); server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server"); username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username"); password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password"); protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol"); dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox"); processedMailbox = (String) this.xmlConfiguration .getProperty("account(" + aIndex + ").processedMailbox"); prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch"); logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName : " + accountName + "\n" + "server : " + server + "\n" + "username : " + username + "\n" + "password : " + password + "\n" + "protocol : " + protocol + "\n" + "dataMailbox : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n" + "prefetch : " + prefetch + "\n"); // get a connection to the mail server Properties props = System.getProperties(); props.setProperty("mail.store.protocol", protocol); props.setProperty("mail.imaps.partialfetch", prefetch); try { // create the imaps mail session this.mailSession = Session.getDefaultInstance(props, null); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe) { try { // pause for 10 seconds logger.debug( "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry."); Thread.sleep(10000L); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe2) { logger.debug("There was an error connecting to the mail server. The " + "message was: " + nspe2.getMessage()); nspe2.printStackTrace(); failed = true; return !failed; } catch (InterruptedException ie) { logger.debug("The thread was interrupted: " + ie.getMessage()); failed = true; return !failed; } } try { this.mailStore.connect(server, username, password); // get folder references for the inbox and processed data box Folder inbox = mailStore.getFolder(dataMailbox); inbox.open(Folder.READ_WRITE); Folder processed = this.mailStore.getFolder(processedMailbox); processed.open(Folder.READ_WRITE); Message[] msgs; while (!inbox.isOpen()) { inbox.open(Folder.READ_WRITE); } msgs = inbox.getMessages(); List<Message> messages = new ArrayList<Message>(); Collections.addAll(messages, msgs); // sort the messages found in the inbox by date sent Collections.sort(messages, new Comparator<Message>() { public int compare(Message message1, Message message2) { int value = 0; try { value = message1.getSentDate().compareTo(message2.getSentDate()); } catch (MessagingException e) { e.printStackTrace(); } return value; } }); logger.debug("Number of messages: " + messages.size()); for (Message message : messages) { // Copy the message to ensure we have the full attachment MimeMessage mimeMessage = (MimeMessage) message; MimeMessage copiedMessage = new MimeMessage(mimeMessage); // determine the sensor serial number for this message String messageSubject = copiedMessage.getSubject(); Date sentDate = copiedMessage.getSentDate(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM"); // The subfolder of the processed mail folder (e.g. 2016-12); String destinationFolder = formatter.format(sentDate); logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber()); String[] subjectParts = messageSubject.split("\\s"); String loggerSerialNumber = "SerialNumber"; if (subjectParts.length > 1) { loggerSerialNumber = subjectParts[2]; } // Do we have a data attachment? If not, there's no data to // process if (copiedMessage.isMimeType("multipart/mixed")) { logger.debug("Message size: " + copiedMessage.getSize()); MimeMessageParser parser = new MimeMessageParser(copiedMessage); try { parser.parse(); } catch (Exception e) { logger.error("Failed to parse the MIME message: " + e.getMessage()); continue; } ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only logger.debug("Has attachments: " + parser.hasAttachments()); for (DataSource dataSource : parser.getAttachmentList()) { if (StringUtils.isNotBlank(dataSource.getName())) { logger.debug( "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), outputStream); messageAttachment = ByteBuffer.wrap(outputStream.toByteArray()); } } // We now have the attachment and serial number. Parse the attachment // for the data components, look up the storXSource based on the serial // number, and push the data to the DataTurbine // parse the binary attachment StorXParser storXParser = new StorXParser(messageAttachment); // iterate through the parsed framesMap and handle each // frame // based on its instrument type BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap(); Collection frameCollection = framesMap.getAll("/frames/frame"); Iterator framesIterator = frameCollection.iterator(); while (framesIterator.hasNext()) { BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next(); // logger.debug(frameMap.toXMLString(1000)); String frameType = (String) frameMap.get("type"); String sensorSerialNumber = (String) frameMap.get("serialNumber"); // handle each instrument type if (frameType.equals("HDR")) { logger.debug("This is a header frame. Skipping it."); } else if (frameType.equals("STX")) { try { // handle StorXSource StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber); // process the data using the StorXSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("SBE")) { try { // handle CTDSource CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber); // process the data using the CTDSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NLB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NDB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else { logger.debug("The frame type " + frameType + " is not recognized. Skipping it."); } } // end while() if (this.sourceMap.get(loggerSerialNumber) != null) { // Note: Use message (not copiedMessage) when setting flags if (!messageProcessed) { logger.info("Failed to process message: " + "Message Number: " + message.getMessageNumber() + " " + "Logger Serial:" + loggerSerialNumber); // leave it in the inbox, flagged as seen (read) message.setFlag(Flags.Flag.SEEN, true); logger.debug("Saw message " + message.getMessageNumber()); } else { // message processed successfully. Create a by-month sub folder if it doesn't exist // Copy the message and flag it deleted Folder destination = processed.getFolder(destinationFolder); boolean created = destination.create(Folder.HOLDS_MESSAGES); inbox.copyMessages(new Message[] { message }, destination); message.setFlag(Flags.Flag.DELETED, true); logger.debug("Deleted message " + message.getMessageNumber()); } // end if() } else { logger.debug("There is no configuration information for " + "the logger serial number " + loggerSerialNumber + ". Please add the configuration to the " + "email.account.properties.xml configuration file."); } // end if() } else { logger.debug("This is not a data email since there is no " + "attachment. Skipping it. Subject: " + messageSubject); } // end if() } // end for() // expunge messages and close the mail server store once we're // done inbox.expunge(); this.mailStore.close(); } catch (MessagingException me) { try { this.mailStore.close(); } catch (MessagingException me2) { failed = true; return !failed; } logger.info( "There was an error reading the mail message. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IOException me) { try { this.mailStore.close(); } catch (MessagingException me3) { failed = true; return !failed; } logger.info("There was an I/O error reading the message part. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IllegalStateException ese) { try { this.mailStore.close(); } catch (MessagingException me4) { failed = true; return !failed; } logger.info("There was an error reading messages from the folder. The " + "message was: " + ese.getMessage()); failed = true; return !failed; } finally { try { this.mailStore.close(); } catch (MessagingException me2) { logger.debug("Couldn't close the mail store: " + me2.getMessage()); } } } return !failed; }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@Test public void receiveMarkAsReadAndDelete() throws Exception { AbstractMailReceiver receiver = new ImapMailReceiver(); ((ImapMailReceiver) receiver).setShouldMarkMessagesAsRead(true); receiver.setShouldDeleteMessages(true); receiver = spy(receiver);/*from w w w . j av a 2 s . c o m*/ receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); Field folderField = AbstractMailReceiver.class.getDeclaredField("folder"); folderField.setAccessible(true); Folder folder = mock(Folder.class); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); folderField.set(receiver, folder); Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); final Message[] messages = new Message[] { msg1, msg2 }; willAnswer(invocation -> { DirectFieldAccessor accessor = new DirectFieldAccessor(invocation.getMock()); int folderOpenMode = (Integer) accessor.getPropertyValue("folderOpenMode"); if (folderOpenMode != Folder.READ_WRITE) { throw new IllegalArgumentException("Folder had to be open in READ_WRITE mode"); } return null; }).given(receiver).openFolder(); willAnswer(invocation -> messages).given(receiver).searchForNewMessages(); willAnswer(invocation -> null).given(receiver).fetchMessages(messages); receiver.receive(); verify(msg1, times(1)).setFlag(Flag.SEEN, true); verify(msg2, times(1)).setFlag(Flag.SEEN, true); verify(receiver, times(1)).deleteMessages((Message[]) Mockito.any()); }
From source file:com.cubusmail.server.mail.imap.IMAPMailbox.java
public void copyMessages(long[] messageIds, String targetFolderId) throws MessagingException { if (!this.currentFolder.isOpen()) { this.currentFolder.open(Folder.READ_WRITE); }/*from ww w .ja va 2 s. c o m*/ IMailFolder targetFolder = getMailFolderById(targetFolderId); if (!targetFolder.isOpen()) { targetFolder.open(Folder.READ_WRITE); } this.currentFolder.copyMessages(messageIds, targetFolder); targetFolder.close(false); }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Mark a given {@link GmailMessage} as unread. * * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()} * @throws GmailException if unable to mark {@link GmailMessage} as unread *///w w w .ja v a2 s.c om public void markAsUnread(int messageNumber) { if (messageNumber <= 0) { throw new GmailException("ImapGmailClient invalid " + "GmailMessage number"); } Folder folder = null; try { final Store store = openGmailStore(); folder = getFolder(this.srcFolder, store); folder.open(Folder.READ_WRITE); Message message = folder.getMessage(messageNumber); if (message.isSet(Flags.Flag.SEEN)) { message.setFlag(Flags.Flag.SEEN, false); } } catch (Exception e) { throw new GmailException( "ImapGmailClient failed marking" + " GmailMessage as unread : " + messageNumber, e); } finally { closeFolder(folder); } }
From source file:com.cubusmail.server.mail.imap.IMAPMailbox.java
public void deleteMessages(long[] messageIds) throws MessagingException { if (messageIds != null && messageIds.length > 0) { if (!this.currentFolder.isOpen()) { this.currentFolder.open(Folder.READ_WRITE); }//from w ww. ja va 2s . c o m Message[] msgs = this.currentFolder.getMessagesById(messageIds); for (int i = 0; i < msgs.length; i++) { msgs[i].setFlag(Flags.Flag.DELETED, true); } this.currentFolder.expunge(msgs); } }