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.DefaultMailReader.java
/** * {@inheritDoc}// w w w . j a v a 2 s .c o m * * @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 Message read(final String folder, final String messageid) throws MessagingException { assert (getMailSource() != null); assert (getMailSource().getHostname() != null); Message message = null; store = null; 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); // Search with message id Message[] messages = fldr.search(new MessageIDTerm(messageid)); if (messages.length > 0) { message = messages[0]; } logger.info("Found message " + message); return message; }
From source file:org.opennms.javamail.JavaReadMailer.java
/** * <p>retrieveMessages</p>// w w w. j a v a 2s . c o m * * @param term a {@link javax.mail.search.SearchTerm} object. * @return a {@link java.util.List} object. * @throws org.opennms.javamail.JavaMailerException if any. */ public List<Message> retrieveMessages(SearchTerm term) throws JavaMailerException { Message[] msgs; Folder mailFolder = null; try { Store store = m_session.getStore(m_config.getReadmailHost().getReadmailProtocol().getTransport()); store.connect(m_config.getReadmailHost().getHost(), (int) m_config.getReadmailHost().getPort(), m_config.getUserAuth().getUserName(), m_config.getUserAuth().getPassword()); mailFolder = store.getFolder(m_config.getMailFolder()); mailFolder.open(Folder.READ_WRITE); msgs = mailFolder.search(term); } 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); } List<Message> msgList = Arrays.asList(msgs); return msgList; }
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 {//w w w .j a va 2 s. c o m 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.funambol.email.items.manager.ImapEntityManager.java
/** * deletes an email//from w ww .ja va 2s . c om * * @param parentId String * @param mailId String * @param GUID String * @param serverItems map with all in the Mail Server CrcSyncItemsInfo * @param source_uri String * @param principalId long * @throws EntityException */ public void removeEmail(String parentId, String mailId, String GUID, Map serverItems, String username, String source_uri, long principalId) throws EntityException { String fullpath = null; try { fullpath = this.ied.getFullPathFromFID(parentId, source_uri, principalId, username); } catch (EntityException e) { throw new EntityException(e); } if (log.isTraceEnabled()) { log.trace("remove item in FID: " + fullpath + " with FMID: " + mailId); } if (fullpath != null) { if (parentId.equalsIgnoreCase(Def.FOLDER_INBOX_ID)) { try { // INBOX timeStart = System.currentTimeMillis(); IMAPFolder inbox = this.imsw.folderInboxOpened; long uid = Long.parseLong(mailId); if (!inbox.isOpen()) { inbox.open(javax.mail.Folder.READ_WRITE); } Message message = inbox.getMessageByUID(uid); IMAPFolder trashFolder = this.imsw.getTrashFolder(); // // If the trash folder does not exists, then create it. // if (!trashFolder.exists()) { if (log.isTraceEnabled()) { log.trace("Trash folder does not exist. Creating Trash folder with path " + trashFolder.getFullName()); } if (trashFolder.create(Folder.HOLDS_MESSAGES)) { trashFolder.open(Folder.READ_WRITE); } } if (message != null) { if (message.isExpunged()) { // // GMail mail server sometimes says an email is expunged // even if it has not been previously deleted. // // Workaround: // // - such behaviour seems to appear after the first time // IMAPFolder.copyMessage method is executed on an open // folder. // // More precisely: the first time method is executed, // the given message is moved correctly; each of // the subsequent execution could work correctly // or not. // // - So: reopen the inbox folder (as: "nothing has // happened"), extract the message, call copyMessage // with that message. // if (inbox.isOpen()) { // // close folder expunging all emails to be expunged // in order to reset state of each email // inbox.close(true); inbox.open(Folder.READ_WRITE); } message = ((IMAPFolder) inbox).getMessageByUID(uid); } // // Following check: message != null is needed in the case // message was expunged (see above). // if (message != null) { // if TRASH folder exists, then copy email to TRASH folder if (trashFolder.exists()) { this.ied.copyEmail(inbox, trashFolder, uid); } // // - With some mail servers the copyEmail method // copies the original message in the destination // folder and leaves the original one in the source // one. // - Other mail servers move the message from the // source folder to the destination folder; thus // the original message cannot be deleted from the // source folder, since it has been already deleted. // // For example: consider the Gmail mail server; when // moving an email from the INBOX folder to the default // trash folder, the copy operation will automatically // delete and expunge the original message from the // source folder; note also that this behavior does // not happen when destination folder is not the default // trash folder). // if (!message.isExpunged()) { // remove email from inbox folder this.ied.removeEmail(inbox, uid); } } } // remove from Cache Inbox Table this.ied.removeEmailInDB(username, Def.PROTOCOL_IMAP, GUID); // remove serverItemsList this.ied.removeItemInServerItems(GUID, serverItems); timeStop = System.currentTimeMillis(); if (log.isTraceEnabled()) { log.trace("removeItem Execution Time: " + (timeStop - timeStart) + " ms"); } } catch (MessagingException e) { throw new EntityException(e); } catch (EntityException e) { throw new EntityException(e); } catch (EmailAccessException e) { throw new EntityException(e); } } else { // SENT - OUTBOX - DRAFTS - TRASH IMAPFolder f = null; EntityException finalExc = null; try { timeStart = System.currentTimeMillis(); // rest of the folders f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath); if (f.exists()) { if (!f.isOpen()) { f.open(Folder.READ_WRITE); } // remove email from mail server this.ied.removeEmail(f, Long.parseLong(mailId)); // remove serverItemsList this.ied.removeItemInServerItems(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("removeItem Execution Time: " + (timeStop - timeStart) + " ms"); } } } catch (MessagingException me) { throw new EntityException(me); } } } } } }
From source file:org.springframework.ws.transport.mail.MailSenderConnection.java
private void openFolder() throws MessagingException { store = session.getStore(storeUri);// ww w .java 2 s .c om store.connect(); folder = store.getFolder(storeUri); if (folder == null || !folder.exists()) { throw new IllegalStateException("No default folder to receive from"); } if (deleteAfterReceive) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } }
From source file:org.wso2.esb.integration.common.utils.servers.GreenMailServer.java
/** * Delete all emails in the inbox./*from w w w .j a va 2 s . c o m*/ * * @param protocol protocol used to connect to the server * @throws MessagingException if we're unable to connect to the store */ public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException { Folder inbox = null; Store store = getConnection(user, protocol); try { inbox = store.getFolder(EMAIL_INBOX); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.getMessages(); for (Message message : messages) { message.setFlag(Flags.Flag.DELETED, true); log.info("Deleted email Subject : " + message.getSubject()); } } finally { if (inbox != null) { inbox.close(true); } if (store != null) { store.close(); } } }
From source file:org.syncope.core.notification.NotificationTest.java
private boolean verifyMail(final String sender, final String subject) { LOG.info("Waiting for notification to be sent..."); try {/* w w w. j a v a 2s . co m*/ Thread.sleep(10000); } catch (InterruptedException e) { } boolean found = false; try { Session session = Session.getDefaultInstance(System.getProperties()); Store store = session.getStore("pop3"); store.connect(pop3Host, 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(); } catch (Throwable t) { LOG.error("Unexpected exception", t); fail("Unexpected exception while fetching e-mail"); } return found; }
From source file:org.wso2.esb.integration.common.utils.MailToTransportUtil.java
/** * Delete all unread emails from inbox/*from ww w. j a v a 2 s .com*/ * * @throws ESBMailTransportIntegrationTestException - Is thrown if an error when deleting the emails */ public static void deleteAllUnreadEmailsFromGmail() throws ESBMailTransportIntegrationTestException { Folder inbox = null; Store store = getConnection(); try { inbox = store.getFolder(EMAIL_INBOX); inbox.open(Folder.READ_WRITE); Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); for (Message message : messages) { message.setFlag(Flags.Flag.DELETED, true); log.info("Deleted email Subject : " + message.getSubject()); } } catch (MessagingException e) { log.error("Error when deleting emails from inbox", e); throw new ESBMailTransportIntegrationTestException("Error when deleting emails from inbox ", e); } finally { if (inbox != null) { try { inbox.close(true); } catch (MessagingException e) { log.warn("Error when closing the email folder : ", e); } } if (store != null) { try { store.close(); } catch (MessagingException e) { log.warn("Error when closing the email store : ", e); } } } }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method read e-mails from Gmail inbox and find whether the notification of particular type is found. * * @param notificationType Notification types supported by publisher and store. * @return whether email is found for particular type. * @throws Exception//from w w w. j a v a2s . c o m */ public static boolean readGmailInboxForNotification(String notificationType) throws Exception { boolean isNotificationMailAvailable = false; long waitTime = 10000; Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Thread.sleep(waitTime); long startTime = System.currentTimeMillis(); long endTime = 0; int count = 1; while (endTime - startTime < 180000 && !isNotificationMailAvailable) { Message[] messages = inbox.getMessages(); for (Message message : messages) { if (!message.isExpunged()) { try { log.info("Mail Subject:- " + message.getSubject()); if (message.getSubject().contains(notificationType)) { isNotificationMailAvailable = true; } // Optional : deleting the mail message.setFlag(Flags.Flag.DELETED, true); } catch (MessageRemovedException e) { log.error("Could not read the message subject. Message is removed from inbox"); } } } endTime = System.currentTimeMillis(); Thread.sleep(waitTime); endTime += count * waitTime; count++; } inbox.close(true); store.close(); return isNotificationMailAvailable; }
From source file:com.abid_mujtaba.fetchheaders.models.Account.java
public SparseArray<Email> fetchEmails() throws MessagingException // Fetches messages from account and uses them to create an array of Email objects. Catches connection exception and re-throws them up the chain. { Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imaps.host", mHost); props.setProperty("mail.imaps.port", "993"); props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Uses SSL to secure communication props.setProperty("mail.imaps.socketFactory.fallback", "false"); Session imapSession = Session.getInstance(props); try {// w w w. j a va 2s.c o m Store store = imapSession.getStore("imaps"); // Connect to server by sending username and password: store.connect(mHost, mUsername, mPassword); mInbox = store.getFolder("Inbox"); mInbox.open(Folder.READ_WRITE); // Open Inbox as read-write since we will be deleting emails later mTrash = store.getFolder("Trash"); if (!mTrash.exists()) { mTrash = store.getFolder("[Gmail]/Trash"); // If a folder labelled "Trash" doesn't exist we attempt to check if it is a Gmail account whose trash folder is differently named mUsesLabels = true; // Set flag to indicate that this account uses Labels rather than folders a la Gmail if (!mTrash.exists()) { mTrash = null; // No trash folder found. Emails will be deleted directly mUsesLabels = false; } } int num = mInbox.getMessageCount(); // Get number of messages in the Inbox if (num > mMaxNumOfEmails) { mMessages = mInbox.getMessages(num - mMaxNumOfEmails + 1, num); // Fetch latest mMaxNumOfEmails emails (seen and unseen both). The oldest email is indexed as 1 and so on. } else { mMessages = mInbox.getMessages(); } FetchProfile fp = new FetchProfile(); fp.add(IMAPFolder.FetchProfileItem.HEADERS); // Fetch header data fp.add(FetchProfile.Item.FLAGS); // Fetch flags mInbox.fetch(mMessages, fp); // Now that the messages have been fetched using the FetchProfile (that is the necessary information has been fetched with them) we sort the message in reverse chronological order Arrays.sort(mMessages, new MessageComparator()); // The sort is accomplished using an instance of a custom comparator that compares messages using DateSent mEmails = new SparseArray<Email>(); for (int ii = 0; ii < mMessages.length; ii++) { Email email = new Email(mMessages[ii]); mEmails.put(ii, email); } return mEmails; } catch (MessagingException e) { Resources.Loge("Exception while attempting to connect to mail server", e); throw e; } // The two above exceptions are caught by this one if they are not explicitly stated above. }