Example usage for javax.mail Message setFlag

List of usage examples for javax.mail Message setFlag

Introduction

In this page you can find the example usage for javax.mail Message setFlag.

Prototype

public void setFlag(Flags.Flag flag, boolean set) throws MessagingException 

Source Link

Document

Set the specified flag on this message to the specified value.

Usage

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

/**
 * Delete all emails in the inbox.// ww w  . ja  v  a2s . co  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.wso2.esb.integration.common.utils.MailToTransportUtil.java

/**
 * Delete all unread emails from inbox/*from   w ww  .ja  v  a  2  s .c o m*/
 *
 * @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.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
 *///w  ww. j a v a  2 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.cubusmail.mail.util.MessageUtils.java

/**
 * @param msg//from  w  w  w .j a  va  2 s .  c o  m
 * @param flag
 * @param readFlag
 * @throws MessagingException
 */
public static void setMessageFlag(Message msg, Flags.Flag flag, boolean readFlag) throws MessagingException {

    boolean currentFlag = msg.isSet(flag);

    if (currentFlag != readFlag) {
        msg.setFlag(flag, readFlag);
    }
}

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  av a  2  s.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:org.wso2.carbon.registry.es.utils.EmailUtil.java

/**
 * This method read verification e-mail from Gmail inbox and returns the verification URL.
 *
 * @return  verification redirection URL.
 * @throws  Exception/*from  w  ww  .  j  a  v  a  2 s  . c o  m*/
 */
public static String readGmailInboxForVerification() throws Exception {
    boolean isEmailVerified = false;
    long waitTime = 10000;
    String pointBrowserURL = "";
    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 && !isEmailVerified) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());
                    if (message.getSubject().contains("EmailVerification")) {
                        pointBrowserURL = getBodyFromMessage(message);
                        isEmailVerified = 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 pointBrowserURL;
}

From source file:org.nuxeo.cm.mail.actionpipe.EndAction.java

public boolean execute(ExecutionContext context) {
    try {// w  ww  .  j  av  a2  s  .c o m
        Message message = context.getMessage();
        // erase marker: mail has been treated
        message.setFlag(Flag.FLAGGED, false);
        return true;
    } catch (MessagingException e) {
        log.error("Failed to execute EndAction", e);
        return false;
    }
}

From source file:org.springframework.ws.transport.mail.monitor.AbstractMonitoringStrategy.java

/**
 * Deletes the given messages from the given folder. Only invoked when {@link #setDeleteMessages(boolean)} is
 * <code>true</code>./*from  w  w w  .  j  a va2s.c  o  m*/
 *
 * @param folder   the folder to delete messages from
 * @param messages the messages to delete
 * @throws MessagingException in case of JavaMail errors
 */
protected void deleteMessages(Folder folder, Message[] messages) throws MessagingException {
    for (Message message : messages) {
        message.setFlag(Flags.Flag.DELETED, true);
    }
}

From source file:com.yfiton.notifiers.email.EmailNotifierTest.java

private boolean checkEmailReception(String subject, String host, String username, String password)
        throws MessagingException {
    Properties properties = new Properties();
    properties.put("mail.store.protocol", "imaps");
    Session session = Session.getInstance(properties);

    Store store = null;/*from   w w  w .  ja v a2  s. c o  m*/

    try {
        store = session.getStore("imaps");
        store.connect(host, username, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (message.getSubject().equals(subject)) {
                message.setFlag(Flags.Flag.DELETED, true);
                return true;
            }
        }

        inbox.close(true);
    } finally {
        try {
            if (store != null) {
                store.close();
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    return false;
}

From source file:com.trivago.mail.pigeon.mail.MailFacade.java

public void readBounceAccount() throws MessagingException {
    Session session = Session.getDefaultInstance(Settings.create().getConfiguration().getProperties("mail.*"));
    Store store = session.getStore("pop3");

    store.connect();//  w  ww  . j a va  2 s .  com

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);

    if (folder.hasNewMessages()) {
        // Get directory
        Message message[] = folder.getMessages();
        BounceFacade bounceFacade = new BounceFacade();

        for (Message msg : message) {
            boolean isBounce = bounceFacade.processBounce(msg);
            if (isBounce) {
                msg.setFlag(Flags.Flag.SEEN, true);
                msg.saveChanges();
            }
        }
    }

}