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:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Flag a given {@link GmailMessage} as Starred. * * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()} * @throws GmailException if unable to flag {@link GmailMessage} as starred *//*from w w w.j a va 2 s. c o m*/ public void addStar(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.FLAGGED)) { message.setFlag(Flags.Flag.FLAGGED, true); } } catch (Exception e) { throw new GmailException( "ImapGmailClient failed flagging" + " GmailMessage as starred : " + messageNumber, e); } finally { closeFolder(folder); } }
From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java
private Object getMessage(String requestMsgId) { Session session = Session.getInstance(props, null); session.setDebug(log.isTraceEnabled()); Store store = null;//from w w w . ja v a 2s. co m try { store = session.getStore("pop3"); store.connect(username, password); Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER); folder.open(Folder.READ_WRITE); Message[] msgs = folder.getMessages(); log.debug(msgs.length + " replies in reply mailbox"); for (Message m : msgs) { String[] inReplyTo = m.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO); log.debug("Got reply to : " + Arrays.toString(inReplyTo)); if (inReplyTo != null && inReplyTo.length > 0) { for (int j = 0; j < inReplyTo.length; j++) { if (requestMsgId.equals(inReplyTo[j])) { m.setFlag(Flags.Flag.DELETED, true); return m.getContent(); } } } m.setFlag(Flags.Flag.DELETED, true); } folder.close(true); } catch (Exception e) { e.printStackTrace(); } finally { if (store != null) { try { store.close(); } catch (MessagingException ignore) { } store = null; } } return null; }
From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
@SuppressWarnings({ "unchecked" }) public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false);/*from www .ja va 2 s . c o m*/ result.setNrErrors(1); //Get system properties Properties prop = new Properties(); prop.setProperty("mail.pop3s.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //Create session object Session sess = Session.getDefaultInstance(prop, null); sess.setDebug(true); FileObject fileObject = null; Store st = null; Folder f = null; try { int nbrmailtoretrieve = Const.toInt(firstmails, 0); String realOutputFolder = getRealOutputDirectory(); fileObject = KettleVFS.getFileObject(realOutputFolder); // Check if output folder exists if (!fileObject.exists()) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.FolderNotExists.Label", realOutputFolder)); //$NON-NLS-1$ } else { if (fileObject.getType() == FileType.FOLDER) { String host = getRealServername(); String user = getRealUsername(); String pwd = getRealPassword(); if (!getUseSSL()) { //Create POP3 object st = sess.getStore("pop3"); //$NON-NLS-1$ // Try to connect to the server st.connect(host, user, pwd); } else { // Ssupports POP3 connection with SSL, the connection is established via SSL. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.fallback", "false"); //$NON-NLS-1$ //$NON-NLS-2$ prop.setProperty("mail.pop3.port", getRealSSLPort()); //$NON-NLS-1$ prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); //$NON-NLS-1$ URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); //$NON-NLS-1$ //$NON-NLS-2$ st = new POP3SSLStore(sess, url); st.connect(); } if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //$NON-NLS-1$ //Open the INBOX FOLDER // For POP3, the only folder available is the INBOX. f = st.getFolder("INBOX"); //$NON-NLS-1$ if (f == null) { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); //$NON-NLS-1$ } else { // Open folder if (delete) f.open(Folder.READ_WRITE); else f.open(Folder.READ_ONLY); Message messageList[] = f.getMessages(); if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder.Label", f.getName(), //$NON-NLS-1$ String.valueOf(messageList.length))); log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder.Label", //$NON-NLS-1$ f.getName(), String.valueOf(f.getUnreadMessageCount()))); } // Get emails Message msg_list[] = getPOPMessages(f, retrievemails); if (msg_list.length > 0) { List<File> current_file_POP = new ArrayList<File>(); List<String> current_filepath_POP = new ArrayList<String>(); int nb_email_POP = 1; String startpattern = "name"; //$NON-NLS-1$ if (!Const.isEmpty(getRealFilenamePattern())) { startpattern = getRealFilenamePattern(); } for (int i = 0; i < msg_list.length; i++) { if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) { Message msg_POP = msg_list[i]; if (log.isDetailed()) { log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label", //$NON-NLS-1$ msg_list[i].getFrom()[0].toString())); log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.EmailSubject.Label", msg_list[i].getSubject())); //$NON-NLS-1$ } String localfilename_message = startpattern + "_" //$NON-NLS-1$ + StringUtil.getFormattedDateTimeNow(true) + "_" + (i + 1) + ".mail"; //$NON-NLS-1$ //$NON-NLS-2$ if (log.isDetailed()) log.logDetailed(toString(), Messages.getString( "JobGetMailsFromPOP.LocalFilename.Label", localfilename_message)); //$NON-NLS-1$ File filename_message = new File(realOutputFolder, localfilename_message); OutputStream os_filename = new FileOutputStream(filename_message); Enumeration<Header> enums_POP = msg_POP.getAllHeaders(); while (enums_POP.hasMoreElements()) { Header header_POP = enums_POP.nextElement(); os_filename.write(new StringBuffer(header_POP.getName()).append(": ") //$NON-NLS-1$ .append(header_POP.getValue()).append("\r\n").toString().getBytes()); //$NON-NLS-1$ } os_filename.write("\r\n".getBytes()); //$NON-NLS-1$ InputStream in_POP = msg_POP.getInputStream(); byte[] buffer_POP = new byte[1024]; int length_POP = 0; while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) { os_filename.write(buffer_POP, 0, length_POP); } os_filename.close(); nb_email_POP++; current_file_POP.add(filename_message); current_filepath_POP.add(filename_message.getPath()); // Check attachments Object content = msg_POP.getContent(); if (content instanceof Multipart) { handleMultipart(realOutputFolder, (Multipart) content); } // Check if mail has to be deleted if (delete) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); //$NON-NLS-1$ msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true); } } } } result.setNrErrors(0); result.setResult(true); } } else { log.logError(toString(), Messages.getString("JobGetMailsFromPOP.Error.NotAFolder", realOutputFolder)); } } } catch (NoSuchProviderException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.ProviderException", e.getMessage())); //$NON-NLS-1$ } catch (MessagingException e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.MessagingException", e.getMessage())); //$NON-NLS-1$ } catch (Exception e) { log.logError(toString(), Messages.getString("JobEntryGetPOP.GeneralException", e.getMessage())); //$NON-NLS-1$ } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } //close the folder, passing in a true value to expunge the deleted message try { if (f != null) f.close(true); if (st != null) st.close(); } catch (Exception e) { log.logError(toString(), e.getMessage()); } // free memory f = null; st = null; sess = null; } return result; }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Removes Star Flag of a given Starred {@link GmailMessage}. * * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()} * @throws GmailException if unable to remove star flag from {@link GmailMessage} *///from w w w . ja v a 2 s .c o m public void removeStar(int messageNumber) { if (messageNumber <= 0) { throw new GmailException("ImapGmailClient invalid " + "GmailMessage number"); } Folder folder = null; try { final Store store = openGmailStore(); folder = getFolder(ImapGmailLabel.STARRED.getName(), store); folder.open(Folder.READ_WRITE); Message message = folder.getMessage(messageNumber); if (message.isSet(Flags.Flag.FLAGGED)) { message.setFlag(Flags.Flag.FLAGGED, false); } } catch (Exception e) { throw new GmailException( "ImapGmailClient failed removing" + " GmailMessage star flag : " + messageNumber, e); } finally { closeFolder(folder); } }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@Test public void receiveAndDontMarkAsReadButDelete() throws Exception { AbstractMailReceiver receiver = new ImapMailReceiver(); receiver.setShouldDeleteMessages(true); ((ImapMailReceiver) receiver).setShouldMarkMessagesAsRead(false); receiver = spy(receiver);/*w w w . java 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.afterPropertiesSet(); receiver.receive(); verify(msg1, times(0)).setFlag(Flag.SEEN, true); verify(msg2, times(0)).setFlag(Flag.SEEN, true); verify(msg1, times(1)).setFlag(Flag.DELETED, true); verify(msg2, times(1)).setFlag(Flag.DELETED, true); }
From source file:com.funambol.email.items.manager.ImapEntityManager.java
/** * updates a document defined by UID/* ww w .j a v a2 s . co m*/ * * @param FID String * @param FMID String * @param emailToUpdate Email * @param source_uri String * @param principalId long * @return Email * @throws EntityException */ public Email updateEmail(String FID, String FMID, Email emailToUpdate, Map serverItems, String username, String protocol, String source_uri, long principalId) throws EntityException { String fullpath = null; try { fullpath = this.ied.getFullPathFromFID(FID, source_uri, principalId, username); } catch (Exception me) { throw new EntityException(me); } if (log.isTraceEnabled()) { log.trace("updateItem fullpath " + fullpath + "FID: " + FID); } if (fullpath != null) { // the emailItem could be null // i.e. the client send only the read property get flags FlagProperties fp = Utility.getFlags(emailToUpdate); Message msgNew = null; if (emailToUpdate.getEmailItem().getStringRFC2822() != null) { msgNew = createMessage(this.imsw.getSession(), emailToUpdate, FID, false, fp); } if (FID.equalsIgnoreCase(Def.FOLDER_INBOX_ID)) { // INBOX try { timeStart = System.currentTimeMillis(); if (!this.imsw.folderInboxOpened.isOpen()) { this.imsw.folderInboxOpened.open(javax.mail.Folder.READ_WRITE); } // update in the Mail Server UpdatedMessage um = this.ied.updateEmail(FID, FMID, this.imsw.folderInboxOpened, msgNew, fp); long uid = um.getFMID(); long uidv = this.imsw.folderInboxOpened.getUIDValidity(); String GUID = Utility.createIMAPGUID(FID, String.valueOf(uid), String.valueOf(uidv)); emailToUpdate.setUID(new Property(GUID)); timeStop = System.currentTimeMillis(); if (log.isTraceEnabled()) { log.trace("updateItem Execution Time: " + (timeStop - timeStart) + " ms"); } // set the values for the post update operation long crc = createInfo(um, protocol); // update the fnbl_email_inbox this.ied.updateCRCInDB(crc, username, protocol, GUID); // update email to the servetItems list this.ied.updateCRCInServerItems(crc, GUID, serverItems); } catch (MessagingException me) { throw new EntityException(me); } catch (EntityException e) { throw new EntityException(e); } } else { // SENT - DRFATS - TRASH - OUTBOX IMAPFolder f = null; try { timeStart = System.currentTimeMillis(); f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath); if (f.exists()) { if (!f.isOpen()) { f.open(Folder.READ_WRITE); } // update in the Mail Server UpdatedMessage um = this.ied.updateEmail(FID, FMID, f, msgNew, fp); long uid = um.getFMID(); long uidv = f.getUIDValidity(); String GUID = Utility.createIMAPGUID(FID, String.valueOf(uid), String.valueOf(uidv)); emailToUpdate.setUID(new Property(GUID)); // set the values for the post update operation SyncItemInfo sii = createInfo(GUID, null, um, Def.PROTOCOL_IMAP); // update email to the servetItems list this.ied.updateItemInServerItems(sii, GUID, serverItems); } } catch (MessagingException me) { throw new EntityException(me); } catch (EntityException e) { throw new EntityException(e); } finally { if (f != null) { try { if (f.isOpen()) { f.close(true); timeStop = System.currentTimeMillis(); if (log.isTraceEnabled()) { log.trace("updateItem Execution Time: " + (timeStop - timeStart) + " ms"); } } } catch (MessagingException me) { throw new EntityException(me); } } } } } return emailToUpdate; }
From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java
/** * Move {@link GmailMessage} to a given destination folder. * * @param destFolder the destination {@link Folder} name.See {@see ImapGmailLabel} * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()} * @throws GmailException if it fails to move {@link GmailMessage} to the * destination folder/* w ww.java 2s .c o m*/ */ public void moveTo(ImapGmailLabel destFolder, int messageNumber) { if (messageNumber <= 0) { throw new GmailException("ImapGmailClient invalid GmailMessage number"); } Folder fromFolder = null; Folder toFolder = null; try { final Store store = openGmailStore(); fromFolder = getFolder(this.srcFolder, store); fromFolder.open(Folder.READ_WRITE); Message message = fromFolder.getMessage(messageNumber); if (message != null) { toFolder = getFolder(destFolder.getName(), store); if (fromFolder.getURLName().equals(toFolder.getURLName())) { throw new GmailException("ImapGmailClient cannot move " + "GmailMessage within same folder " + "(from " + fromFolder.getFullName() + " to " + toFolder.getFullName() + ")"); } // copy from source folder to destination folder fromFolder.copyMessages(new Message[] { message }, toFolder); // move the copied message to trash folder moveToTrash(new GmailMessage[] { new JavaMailGmailMessage(message) }); } } catch (GmailException ge) { throw ge; } catch (Exception e) { throw new GmailException( "ImapGmailClient failed moving" + " GmailMessage from " + fromFolder.getFullName(), e); } finally { closeFolder(fromFolder); } }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@Test public void receiveAndIgnoreMarkAsReadDontDelete() throws Exception { AbstractMailReceiver receiver = new ImapMailReceiver(); receiver = spy(receiver);// ww w. ja va2 s . co 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(0)).deleteMessages((Message[]) Mockito.any()); }
From source file:org.gcaldaemon.core.GmailEntry.java
public final GmailMessage[] receive(String title) throws Exception { // Open 'INBOX' folder Folder inbox = mailbox.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); if (messages == null || messages.length == 0) { return new GmailMessage[0]; }//from ww w .ja va 2s . co m // Loop on messages LinkedList list = new LinkedList(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; if (!msg.isSet(Flag.SEEN)) { String subject = msg.getSubject(); if (title == null || title.length() == 0 || title.equals(subject)) { GmailMessage gm = new GmailMessage(); Address[] from = msg.getFrom(); msg.setFlag(Flag.SEEN, true); if (from == null || from.length == 0) { continue; } gm.subject = subject; gm.from = from[0].toString(); gm.memo = String.valueOf(msg.getContent()); list.addLast(gm); } } } inbox.close(true); // Return the array of the messages GmailMessage[] array = new GmailMessage[list.size()]; list.toArray(array); return array; }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testEightBitMessage() throws Exception { Store lstore = session.getStore(PROTOCOL); lstore.connect(imapServer.getHost(), imapServer.getPort(), ADMIN_USER_NAME, ADMIN_USER_PASSWORD); String folderName = "Alfresco IMAP/" + IMAP_FOLDER_NAME; IMAPFolder lfolder = (IMAPFolder) lstore.getFolder(folderName); lfolder.open(Folder.READ_WRITE); InputStream messageFileInputStream1 = null; InputStream messageFileInputStream2 = null; try {/*from w w w .j a v a 2s . c o m*/ ClassPathResource fileResource = new ClassPathResource("imap/test-8bit-message.eml"); messageFileInputStream1 = new FileInputStream(fileResource.getFile()); Message message = new MimeMessage(Session.getDefaultInstance(new Properties()), messageFileInputStream1); String subject = message.getSubject(); // get original bytes for further comparation messageFileInputStream2 = new FileInputStream(fileResource.getFile()); byte[] original = ASCIIUtility.getBytes(messageFileInputStream2); Message[] messages = { message }; lfolder.appendMessages(messages); // The search is not implemented. // SearchTerm term = new HeaderTerm("X-Alfresco-Unique", "test8bit"); // messages = folder.search(term); // So wee need to get our test message's UID from the repo String messageXPath = companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME + "/*[like(@cm:title, $cm:title, true)]"; QueryParameterDefinition[] params = new QueryParameterDefinition[1]; params[0] = new QueryParameterDefImpl(ContentModel.PROP_TITLE, serviceRegistry.getDictionaryService().getDataType(DataTypeDefinition.TEXT), true, subject); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, messageXPath, params, namespaceService, true); // does the message exist assertEquals(1, nodeRefs.size()); NodeRef messageNodeRef = nodeRefs.get(0); // get message UID Long dbid = (Long) nodeService.getProperty(messageNodeRef, ContentModel.PROP_NODE_DBID); // fetch the massage RFC822DATA data = getRFC822Message(lfolder, dbid); assertNotNull("Can't fetch a message from the repositiry", data); byte[] processed = ASCIIUtility.getBytes(data.getByteArrayInputStream()); assertTrue("Original message doesn't coincide to the message processed by the repository", Arrays.equals(original, processed)); } finally { if (messageFileInputStream1 != null) messageFileInputStream1.close(); if (messageFileInputStream2 != null) messageFileInputStream2.close(); } // close connection lfolder.close(true); lstore.close(); }