Example usage for javax.mail Folder READ_WRITE

List of usage examples for javax.mail Folder READ_WRITE

Introduction

In this page you can find the example usage for javax.mail Folder READ_WRITE.

Prototype

int READ_WRITE

To view the source code for javax.mail Folder READ_WRITE.

Click Source Link

Document

The state and contents of this folder can be modified.

Usage

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder and read messages until it founds the magic subject,
 * then gets the attachment which contains the data and return the serialized object stored.
 *//*from  w  ww  .java2  s .c o  m*/
protected static Object readUserPreferencesFromIMAP(Log logger, User user, IMAPStore iStore, String folderName,
        String magicType) throws MessagingException, IOException, ClassNotFoundException {
    Folder folder = iStore.getFolder(folderName);
    if (folder.exists()) {
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }
        Message message = null;
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (magicType.equals(msg.getSubject())) {
                message = msg;
                break;
            }
        }
        if (message != null) {
            Object con = message.getContent();
            if (con instanceof Multipart) {
                Multipart mp = (Multipart) con;
                for (int i = 0; i < mp.getCount(); i++) {
                    BodyPart part = mp.getBodyPart(i);
                    if (part.getContentType().toLowerCase().startsWith(HUPA_DATA_MIME_TYPE)) {
                        ObjectInputStream ois = new ObjectInputStream(part.getInputStream());
                        Object o = ois.readObject();
                        ois.close();
                        logger.info("Returning user preferences of type " + magicType + " from imap folder + "
                                + folderName + " for user " + user);
                        return o;
                    }
                }
            }
        }
    }
    return null;
}

From source file:org.apache.axis2.transport.mail.MailClient.java

public int checkInbox(int mode) throws MessagingException, IOException {
    int numMessages = 0;

    if (mode == 0) {
        return 0;
    }/*w ww.  j  a  v a 2 s  . co m*/

    boolean show = (mode & SHOW_MESSAGES) > 0;
    boolean clear = (mode & CLEAR_MESSAGES) > 0;
    String action = (show ? "Show" : "") + ((show && clear) ? " and " : "") + (clear ? "Clear" : "");

    log.info(action + " INBOX for " + from);

    Store store = session.getStore();

    store.connect();

    Folder root = store.getDefaultFolder();
    Folder inbox = root.getFolder("inbox");

    inbox.open(Folder.READ_WRITE);

    Message[] msgs = inbox.getMessages();

    numMessages = msgs.length;

    if ((msgs.length == 0) && show) {
        log.info("No messages in inbox");
    }

    for (int i = 0; i < msgs.length; i++) {
        MimeMessage msg = (MimeMessage) msgs[i];

        if (show) {
            log.info("    From: " + msg.getFrom()[0]);
            log.info(" Subject: " + msg.getSubject());
            log.info(" Content: " + msg.getContent());
        }

        if (clear) {
            msg.setFlag(Flags.Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();

    return numMessages;
}

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 www. j ava2s  .c o 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:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java

@Test
public void testOpenImapConnection() throws Exception {
    Store mailAccount = null;/*from  w w  w.  j a v  a  2s .  com*/
    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 --
        javax.mail.Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
        MailProcessor processor = new MailProcessor();
        MessageListener mailingList = mock(MessageListener.class);
        when(mailingList.checkSender(anyString())).thenReturn(Boolean.TRUE);
        when(mailingList.getComponentId()).thenReturn("mailingList38");
        MessageEvent event = new MessageEvent();
        for (javax.mail.Message message : msgs) {
            processor.prepareMessage((MimeMessage) message, mailingList, event);
        }
        assertThat(event.getMessages(), is(notNullValue()));
        assertThat(event.getMessages().size(), is(msgs.length));
        for (com.silverpeas.mailinglist.service.model.beans.Message message : event.getMessages()) {
            assertThat(message, is(notNullValue()));
            assertThat(message.getMessageId(), is(notNullValue()));
        }
    } finally {
        // -- Close down nicely --
        if (inbox != null) {
            inbox.close(false);
        }
        if (mailAccount != null) {
            mailAccount.close();
        }
    }
}

From source file:edu.hawaii.soest.hioos.storx.StorXEmailUtil.java

/**
 * Creates a set of folders in the GMail accout based on year and month
 * to organize the backlog of data and make it more manageable to process
 * //w  w  w. j  a va 2 s  .com
 * @param parent - the parent folder to make the folders in
 * @throws MessagingException 
 */
public static void createFolders(String parent) throws MessagingException {
    ArrayList<String> years = getYears();
    ArrayList<String> months = getMonths();

    targetParentFolder = mailStore.getFolder(parent);
    targetParentFolder.open(Folder.READ_WRITE);

    boolean created = false;
    for (String year : years) {
        for (String month : months) {
            String folderName = year + "-" + month;
            Folder newFolder = targetParentFolder.getFolder(folderName);
            created = newFolder.create(Folder.HOLDS_MESSAGES);
            log.debug("Created " + folderName + " : " + created);

        }
    }

}

From source file:org.nuxeo.cm.event.MailInjectionListener.java

public void handleEvent(Event event) throws ClientException {
    MailService mailService = Framework.getService(MailService.class);
    MessageActionPipe pipe = mailService.getPipe(MAILBOX_PIPE);

    Visitor visitor = new Visitor(pipe);
    Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());

    Folder rootFolder = null;//from   ww  w.j av  a  2  s . c  o  m

    try (CoreSession session = CoreInstance.openCoreSessionSystem(null)) {
        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();
        initialExecutionContext.put(AbstractCaseManagementMailAction.CORE_SESSION_KEY, session);
        initialExecutionContext.put(AbstractCaseManagementMailAction.MIMETYPE_SERVICE_KEY,
                Framework.getService(MimetypeRegistry.class));
        initialExecutionContext.put(AbstractCaseManagementMailAction.CASEMANAGEMENT_SERVICE_KEY,
                Framework.getService(CaseDistributionService.class));

        // open store
        Store store = mailService.getConnectedStore(IMPORT_MAILBOX);
        rootFolder = store.getFolder(INBOX);
        rootFolder.open(Folder.READ_WRITE);
        Flags flags = new Flags();
        flags.add(Flag.SEEN);
        SearchTerm term = new FlagTerm(flags, false);
        Message[] unreadMessages = rootFolder.search(term);

        // perform import
        visitor.visit(unreadMessages, initialExecutionContext);

        // save session
        session.save();

        if (rootFolder.isOpen()) {
            try {
                rootFolder.close(true);
            } catch (MessagingException e) {
                log.error(e.getMessage(), e);
            }
        }
    } catch (MessagingException e) {
        log.error(e, e);
    }
}

From source file:org.apache.juddi.v3.tck.UDDI_090_Smtp_ExternalTest.java

/**
 * gets all current messages from the mail server and returns the number
 * of messages containing the string, messages containing the string are
 * deleted from the mail server String is the body of each message
 *
 * @return number of matching and deleted messages
 * @param contains a string to search for
 *//* w  w  w.  j  av  a 2  s .c  o  m*/
private static int fetchMail(String contains) {

    //final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    /* Set the mail properties */
    Properties properties = TckPublisher.getProperties();
    // Set manual Properties

    int found = 0;
    Session session = Session.getDefaultInstance(properties, null);
    Store store = null;
    try {
        store = session.getStore("pop3");

        store.connect(properties.getProperty("mail.pop3.host"),
                Integer.parseInt(properties.getProperty("mail.pop3.port", "110")),
                properties.getProperty("mail.pop3.username"), properties.getProperty("mail.pop3.password"));
        /* Mention the folder name which you want to read. */
        // inbox = store.getDefaultFolder();
        // inbox = inbox.getFolder("INBOX");
        Folder inbox = store.getFolder("INBOX");

        /* Open the inbox using store. */
        inbox.open(Folder.READ_WRITE);

        Message messages[] = inbox.getMessages();

        for (int i = 0; i < messages.length; i++) {

            MimeMessageParser p = new MimeMessageParser(new MimeMessage(session, messages[i].getInputStream()));
            Enumeration allHeaders = p.getMimeMessage().getAllHeaders();
            while (allHeaders.hasMoreElements()) {
                Object j = allHeaders.nextElement();
                if (j instanceof javax.mail.Header) {
                    javax.mail.Header msg = (javax.mail.Header) j;
                    logger.info("XML as message header is " + msg.getValue());
                    if (msg.getValue().contains(contains)) {
                        //found it
                        messages[i].setFlag(Flags.Flag.DELETED, true);
                        found++;
                    }
                }
            }
            for (int k = 0; k < p.getAttachmentList().size(); k++) {
                InputStream is = p.getAttachmentList().get((k)).getInputStream();
                QuotedPrintableCodec qp = new QuotedPrintableCodec();
                // If "is" is not already buffered, wrap a BufferedInputStream
                // around it.
                if (!(is instanceof BufferedInputStream)) {
                    is = new BufferedInputStream(is);
                }
                int c;
                StringBuilder sb = new StringBuilder();
                System.out.println("Message : ");
                while ((c = is.read()) != -1) {
                    sb.append(c);
                    System.out.write(c);
                }
                is.close();
                String decoded = qp.decode(sb.toString());
                logger.info("decode message is " + decoded);
                if (decoded.contains(contains)) {
                    //found it
                    messages[i].setFlag(Flags.Flag.DELETED, true);
                    found++;
                }
            }

        }
        inbox.close(true);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (Exception ex) {
            }
        }
    }
    return found;
}

From source file:com.ieprofile.helper.gmail.OAuth2Authenticator.java

/**
 * Connects and authenticates to an IMAP server with OAuth2. You must have
 * called {@code initialize}./*from   w ww  .  ja v a2s. c o m*/
 *
 * @param host Hostname of the imap server, for example {@code
 *     imap.googlemail.com}.
 * @param port Port of the imap server, for example 993.
 * @param userEmail Email address of the user to authenticate, for example
 *     {@code oauth@gmail.com}.
 * @param oauthToken The user's OAuth token.
 * @param debug Whether to enable debug logging on the IMAP connection.
 *
 * @return An authenticated IMAPStore that can be used for IMAP operations.
 */
public List<MessageBean> connectToImap(String host, int port, String userEmail, String oauthToken,
        boolean debug) throws Exception {
    Properties props = new Properties();
    props.put("mail.imaps.sasl.enable", "true");
    props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
    props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
    Session session = Session.getInstance(props);
    session.setDebug(debug);

    final URLName unusedUrlName = null;
    IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
    final String emptyPassword = "";
    store.connect(host, port, userEmail, emptyPassword);
    Folder inbox = store.getFolder("Inbox");
    inbox.open(Folder.READ_WRITE);
    Message messages[] = inbox.getMessages();
    int messageCount = inbox.getMessageCount();
    List<String> attachments = new ArrayList<String>();
    LinkedList<MessageBean> listMessages = emailListener.sendMessage(messages, attachments);
    emailRepo.addAllMessages(listMessages);

    emailListener.folder = inbox;
    emailListener.started = false;
    emailListener.start();

    //ArrayList<String> attachments = new ArrayList<String>();
    //LinkedList<MessageBean> listMessages = getPart(messages, attachments);

    //store.close();
    return emailRepo.getMessages();
}

From source file:com.szmslab.quickjavamail.receive.MailReceiver.java

/**
 * ????// w  w w .  j a  va2  s.c om
 *
 * @param callback
 *            ??1???
 * @throws Exception
 */
public void execute(ReceiveIterationCallback callback) throws Exception {
    final Session session = useDefaultSession
            ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator())
            : Session.getInstance(properties.getProperties(), properties.getAuthenticator());
    session.setDebug(isDebug);

    Store store = null;
    Folder folder = null;
    try {
        store = session.getStore(properties.getProtocol());
        store.connect();

        folder = store.getFolder(folderName);
        folder.open(readonly ? Folder.READ_ONLY : Folder.READ_WRITE);

        final Message messages[] = folder.getMessages();
        for (Message message : messages) {
            MessageLoader loader = new MessageLoader(message, !readonly);
            boolean isContinued = callback.iterate(loader);
            if (!readonly && loader.isDeleted()) {
                message.setFlag(Flags.Flag.DELETED, loader.isDeleted());
            }
            if (!isContinued) {
                break;
            }
        }
    } finally {
        if (folder != null) {
            try {
                folder.close(!readonly);
            } catch (MessagingException e) {
                System.out.println(e);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                System.out.println(e);
            }
        }
    }
}

From source file:org.wso2.esb.integration.common.utils.servers.GreenMailServer.java

/**
 * Check mail folder for an email using subject.
 *
 * @param emailSubject Email subject/*from  w w  w  .  java 2 s .co  m*/
 * @param folder       mail folder to check for an email
 * @param protocol     protocol used to connect to the server
 * @return whether mail received or not
 * @throws MessagingException if we're unable to connect to the store
 */
private static boolean isMailReceivedBySubject(String emailSubject, String folder, String protocol,
        GreenMailUser user) throws MessagingException {
    boolean emailReceived = false;
    Folder mailFolder;
    Store store = getConnection(user, protocol);
    try {
        mailFolder = store.getFolder(folder);
        mailFolder.open(Folder.READ_WRITE);
        SearchTerm searchTerm = new AndTerm(new SubjectTerm(emailSubject), new BodyTerm(emailSubject));
        Message[] messages = mailFolder.search(searchTerm);
        for (Message message : messages) {
            if (message.getSubject().contains(emailSubject)) {
                log.info("Found the Email with Subject : " + emailSubject);
                emailReceived = true;
                break;
            }
        }
    } finally {
        if (store != null) {
            store.close();
        }
    }
    return emailReceived;
}