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.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * Marks the supplied message as being read.
 *
 * @throws MessagingException if there was a problem
 *///from  ww w .  j a v  a2  s  . c  o  m
public void markMsgRead(Message msg) throws MessagingException {
    msg.setFlag(Flags.Flag.SEEN, true);
    log.debug("Message marked as read");
}

From source file:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * Marks the supplied message for deletion. The message will actually be
 * deleted when the folder it is in is closed.
 *
 * @throws MessagingException if there was a problem
 */// w  ww. j a  va2s .c o  m
public void deleteMsg(Message msg) throws MessagingException {
    msg.setFlag(Flags.Flag.DELETED, true);
    log.debug("Message marked for deletion from [" + msg.getFolder() + "]");
}

From source file:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * Resets the read flag for the supplied message.
 *
 * @throws MessagingException if there was a problem
 *//*from  w  w w. j a va  2s.  co m*/
public void resetMsgReadFlag(Message msg, boolean origState) throws MessagingException {
    msg.setFlag(Flags.Flag.SEEN, origState);
    log.debug("Message reset to " + (origState ? "" : "un") + "read");
}

From source file:com.robin.utilities.Utilities.java

/**
 * A utility that waits for a gmail mailbox to receive a new message with
 * according to a given SearchTerm. Only "Not seen" messages are searched,
 * and all match is set as SEEN, but just the first occurrence of the
 * matching message is returned./*from  w  w w  .  j a va2s.com*/
 * @param username the mailbox owner's user name (no @gmail.com required).
 * @param pass the user password protecting this mailbox
 * @param st the SearchTerm built to filter messages
 * @param timeoutMessage the message to show when no such mail found within
 *            timeout
 * @param timeout The maximum amount of time to wait in milliseconds.
 * @return a last from the new messages thats match the st conditions
 */
public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st,
        final String timeoutMessage, final long timeout) {
    String host = "imap.gmail.com";
    final long retryTime = 1000;

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.put("mail.imaps.ssl.trust", "*");
    EMail email = null;
    Session session = Session.getDefaultInstance(props, null);
    try {
        Store store = session.getStore("imaps");
        store.connect(host, username, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox)
                .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS)
                .withMessage(timeoutMessage);
        email = waitForMail.until(new Function<Folder, EMail>() {
            @Override
            public EMail apply(final Folder inbox) {
                EMail email = null;
                FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
                SearchTerm sst = new AndTerm(ft, st);
                try {
                    inbox.getMessageCount();
                    Message[] messages = inbox.search(sst);
                    for (Message message : messages) {
                        message.setFlag(Flag.SEEN, true);
                    }
                    if (messages.length > 0) {
                        return new EMail(messages[0]);
                    }
                } catch (MessagingException e) {
                    Assert.fail(e.getMessage());
                }
                return email;
            }
        });
        inbox.close(false);
        store.close();
    } catch (MessagingException e) {
        Assert.fail(e.getMessage());
    }
    return email;
}

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

/**
 * ????/* w w w. jav  a  2 s.c o m*/
 *
 * @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:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start,
        final int deleteCount, final String user, final String password) throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);/*w w w  . j a v a2s .  c om*/
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m = deleteCount == -1 ? f.getMessages()
            : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
        message.setFlag(Flag.DELETED, true);
        logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
        d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();

}

From source file:org.apache.camel.component.mail.MailConsumer.java

/**
 * Strategy to flag the message after being processed.
 *
 * @param mail the mail message//from  www .  j a va2  s . c om
 * @param exchange the exchange
 */
protected void processCommit(Message mail, Exchange exchange) {
    try {
        if (getEndpoint().getConfiguration().isDelete()) {
            LOG.debug("Exchange processed, so flagging message as DELETED");
            mail.setFlag(Flags.Flag.DELETED, true);
        } else {
            LOG.debug("Exchange processed, so flagging message as SEEN");
            mail.setFlag(Flags.Flag.SEEN, true);
        }
    } catch (MessagingException e) {
        LOG.warn("Error occurred during flagging message as DELETED/SEEN", e);
        exchange.setException(e);
    }
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * {@inheritDoc}/*from w w w  .  java  2s  . co  m*/
 * 
 * @see ch.entwine.weblounge.common.scheduler.JobWorker#execute(java.lang.String,
 *      java.util.Dictionary)
 */
public void execute(String name, Dictionary<String, Serializable> ctx) throws JobException {

    Site site = (Site) ctx.get(Site.class.getName());

    // Make sure the site is ready to accept content
    if (site.getContentRepository().isReadOnly()) {
        logger.warn("Unable to publish e-mail messages to site '{}': repository is read only", site);
        return;
    }

    WritableContentRepository repository = (WritableContentRepository) site.getContentRepository();

    // Extract the configuration from the job properties
    String provider = (String) ctx.get(OPT_PROVIDER);
    Account account = null;
    try {
        if (StringUtils.isBlank(provider)) {
            provider = DEFAULT_PROVIDER;
        }
        account = new Account(ctx);
    } catch (IllegalArgumentException e) {
        throw new JobException(this, e);
    }

    // Connect to the server
    Properties sessionProperties = new Properties();
    Session session = Session.getDefaultInstance(sessionProperties, null);
    Store store = null;
    Folder inbox = null;

    try {

        // Connect to the server
        try {
            store = session.getStore(provider);
            store.connect(account.getHost(), account.getLogin(), account.getPassword());
        } catch (NoSuchProviderException e) {
            throw new JobException(this, "Unable to connect using unknown e-mail provider '" + provider + "'",
                    e);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to " + provider + " account " + account, e);
        }

        // Open the account's inbox
        try {
            inbox = store.getFolder(INBOX);
            if (inbox == null)
                throw new JobException(this, "No inbox found at " + account);
            inbox.open(Folder.READ_WRITE);
        } catch (MessagingException e) {
            throw new JobException(this, "Error connecting to inbox at " + account, e);
        }

        // Get the messages from the server
        try {
            for (Message message : inbox.getMessages()) {
                if (!message.isSet(Flag.SEEN)) {
                    try {
                        Page page = aggregate(message, site);
                        message.setFlag(Flag.DELETED, true);
                        repository.put(page, true);
                        logger.info("E-Mail message published at {}", page.getURI());
                    } catch (Exception e) {
                        logger.info("E-Mail message discarded: {}", e.getMessage());
                        message.setFlag(Flag.SEEN, true);
                        // TODO: Reply to sender if the "from" field exists
                    }
                }
            }
        } catch (MessagingException e) {
            throw new JobException(this, "Error loading e-mail messages from inbox", e);
        }

        // Close the connection
        // but don't remove the messages from the server
    } finally {
        if (inbox != null) {
            try {
                inbox.close(true);
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing inbox", e);
            }
        }
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new JobException(this, "Error closing connection to e-mail server", e);
            }
        }
    }

}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * /* w w  w  . ja  va  2  s . c  o  m*/
 */
@Override
public List<IMessage> receive(boolean clear) {
    List<IMessage> result = new ArrayList<IMessage>();

    try {
        String user = properties.getProperty("pop3.login.user");
        String password = properties.getProperty("pop3.login.password");

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

        Properties pop3Props = new Properties();

        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port"));
        pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port"));

        URLName url = new URLName("pop3", properties.getProperty("pop3.host"),
                Integer.valueOf(properties.getProperty("pop3.port")), "", user, password);

        Session session = Session.getInstance(pop3Props, null);
        Store store = new POP3SSLStore(session, url);
        store.connect();

        // Open the Folder
        Folder folder = store.getDefaultFolder();
        folder = folder.getFolder("INBOX");

        if (folder == null) {
            throw new RuntimeException("Invalid folder INBOX");
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }

        int count = folder.getMessageCount();
        // Message numbers start at 1
        for (int i = 1; i <= count; i++) {
            // Get a message by its sequence number
            Message m = folder.getMessage(i);
            Address[] from = m.getFrom();
            String type = from[0].getType();

            IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m));

            result.add(message);

            // delete message ?
            if (clear)
                m.setFlag(Flags.Flag.DELETED, true);
        }

        // "true" actually deletes flagged messages from folder
        folder.close(clear);
        store.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

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 w  w  .j ava2  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);
    }
}