Example usage for javax.mail Flags Flags

List of usage examples for javax.mail Flags Flags

Introduction

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

Prototype

public Flags(String flag) 

Source Link

Document

Construct a Flags object initialized with the given user flag.

Usage

From source file:org.apache.hupa.server.handler.AbstractDeleteMessageHandler.java

public DeleteMessageResult executeInternal(Action action, ExecutionContext context) throws ActionException {
    org.apache.hupa.shared.data.IMAPFolder folder = action.getFolder();
    User user = getUser();//from ww w  .ja  v a2s .c o  m
    try {
        IMAPStore store = cache.get(user);
        com.sun.mail.imap.IMAPFolder f = (com.sun.mail.imap.IMAPFolder) store.getFolder(folder.getFullName());
        // check if the folder is open, if not open it "rw"
        if (f.isOpen() == false) {
            f.open(com.sun.mail.imap.IMAPFolder.READ_WRITE);
        }

        Message[] mArray = getMessagesToDelete(action);

        // check if the delete was triggered not in the trash folder
        if (folder.getFullName().equalsIgnoreCase(user.getSettings().getTrashFolderName()) == false) {
            com.sun.mail.imap.IMAPFolder trashFolder = (com.sun.mail.imap.IMAPFolder) store
                    .getFolder(user.getSettings().getTrashFolderName());

            boolean trashFound = false;
            // if the trash folder does not exist we create it
            if (trashFolder.exists() == false) {
                trashFound = trashFolder.create(com.sun.mail.imap.IMAPFolder.READ_WRITE);
            } else {
                trashFound = true;
            }

            // Check if we are able to copy the messages to the trash folder
            if (trashFound) {
                // copy the messages to the trashfolder
                f.copyMessages(mArray, trashFolder);
            }
        }

        // delete the messages from the folder
        f.setFlags(mArray, new Flags(Flags.Flag.DELETED), true);

        try {
            f.expunge(mArray);
            f.close(false);
        } catch (MessagingException e) {
            // prolly UID expunge is not supported
            f.close(true);
        }
        return new DeleteMessageResult(user, folder, mArray.length);

    } catch (MessagingException e) {
        logger.error("Error while deleting messages for user " + user + " in folder" + action.getFolder(), e);
        throw new ActionException("Error while deleting messages");
    }
}

From source file:com.hs.mail.imap.message.response.FetchResponseBuilder.java

public FetchResponse build(long msgnum, FetchProfile fp, FetchData fd) {
    FetchResponse response = new FetchResponse(msgnum);
    if (fp.contains(FetchProfile.Item.FLAGS)) {
        response.setFlags(fd.getFlags());
    }//from w ww . j a  va 2  s.c  om
    if (fp.contains(FetchData.FetchProfileItem.INTERNALDATE)) {
        response.setInternalDate(fd.getInternalDate());
    }
    if (fp.contains(FetchData.FetchProfileItem.SIZE)) {
        response.setSize(new Long(fd.getSize()));
    }
    if (fp.contains(FetchProfile.Item.ENVELOPE)) {
        Envelope envelope = buildEnvelope(fd.getPhysMessageID());
        response.setEnvelope(envelope);
    }
    if (fp.contains(FetchData.FetchProfileItem.BODY) || fp.contains(FetchData.FetchProfileItem.BODYSTRUCTURE)) {
        MimeDescriptor descriptor = getBodyStructure(fd);
        if (fp.contains(FetchData.FetchProfileItem.BODY)) {
            response.setBody(descriptor);
        }
        if (fp.contains(FetchData.FetchProfileItem.BODYSTRUCTURE)) {
            response.setBodyStructure(descriptor);
        }
    }
    if (fp.contains(FetchData.FetchProfileItem.UID)) {
        response.setUid(new Long(fd.getMessageID()));
    }
    BodyFetchItem item = getBodyFetchItem(fp);
    if (item != null) {
        try {
            byte[] contents = bodyFetch(fd, item);
            Content content = buildBodyContent(contents, item);
            response.setContent(content);
            // Check if this fetch will cause the "SEEN" flag to be set
            // on this message.
            if (!item.isPeek()) {
                if (fd.getFlags() == null || !fd.getFlags().contains(Flags.Flag.SEEN)) {
                    manager.setFlags(fd.getMessageID(), new Flags(Flags.Flag.SEEN), false, true);
                }
            }
        } catch (Exception e) {
            // FIXME The main reason for this exception is that the message
            // file is not exist.
            // If we throw exception, all subsequent fetch will fail.
            // So, ignore this exception at now.
        }
    }
    return response;
}

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

protected int poll() throws Exception {
    // must reset for each poll
    shutdownRunningTask = null;/*  w ww .j a va2 s  .  com*/
    pendingExchanges = 0;
    int polledMessages = 0;

    ensureIsConnected();

    if (store == null || folder == null) {
        throw new IllegalStateException("MailConsumer did not connect properly to the MailStore: "
                + getEndpoint().getConfiguration().getMailStoreLogInformation());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Polling mailfolder: " + getEndpoint().getConfiguration().getMailStoreLogInformation());
    }

    if (getEndpoint().getConfiguration().getFetchSize() == 0) {
        LOG.warn(
                "Fetch size is 0 meaning the configuration is set to poll no new messages at all. Camel will skip this poll.");
        return 0;
    }

    // ensure folder is open
    if (!folder.isOpen()) {
        folder.open(Folder.READ_WRITE);
    }

    try {
        int count = folder.getMessageCount();
        if (count > 0) {
            Message[] messages;

            // should we process all messages or only unseen messages
            if (getEndpoint().getConfiguration().isUnseen()) {
                messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
            } else {
                messages = folder.getMessages();
            }

            polledMessages = processBatch(CastUtils.cast(createExchanges(messages)));
        } else if (count == -1) {
            throw new MessagingException("Folder: " + folder.getFullName() + " is closed");
        }
    } catch (Exception e) {
        handleException(e);
    } finally {
        // need to ensure we release resources
        try {
            if (folder.isOpen()) {
                folder.close(true);
            }
        } catch (Exception e) {
            // some mail servers will lock the folder so we ignore in this case (CAMEL-1263)
            LOG.debug("Could not close mailbox folder: " + folder.getName(), e);
        }
    }

    return polledMessages;
}

From source file:org.apache.james.jmap.model.Keyword.java

public Flags asFlags() {
    return asSystemFlag().map(Flags::new).orElse(new Flags(flagName));
}

From source file:com.sonicle.webtop.mail.bol.model.ImapQuery.java

public static SearchTerm toSearchTerm(String allFlagStrings[], List<Tag> atags, QueryObj query,
        DateTimeZone timezone) {//from  w  ww  . j  a  v  a  2 s.c  om
    SearchTerm searchTerm = null;
    ArrayList<SearchTerm> terms = new ArrayList<SearchTerm>();

    if (query != null) {
        ArrayList<Condition> conditionsList = query.conditions;
        String allText = query.allText;

        if (allText != null && allText.trim().length() > 0) {
            SearchTerm defaultterms[] = toDefaultSearchTerm(allText);
            terms.add(new OrTerm(defaultterms));
        }

        conditionsList.forEach(condition -> {
            String key = condition.keyword;
            String value = condition.value;

            if (key.equals(FROM)) {
                terms.add(new FromStringTerm(value));
            } else if (key.equals(TO)) {
                terms.add(new RecipientStringTerm(Message.RecipientType.TO, value));
            } else if (key.equals(SUBJECT)) {
                terms.add(new SubjectTerm(value));
            } else if (key.equals(MESSAGE)) {
                terms.add(new BodyTerm(value));
            } else if (key.equals(EVERYWHERE)) {
                SearchTerm anyterms[] = toAnySearchTerm(value);
                terms.add(new OrTerm(anyterms));
            } else if (key.equals(AFTER)) {
                Date afterDate = ImapQuery.parseDate(value, timezone);
                terms.add(new ReceivedDateTerm(DateTerm.GE, afterDate));
                terms.add(new SentDateTerm(DateTerm.GE, afterDate));
            } else if (key.equals(BEFORE)) {
                Date beforeDate = ImapQuery.parseDate(value, timezone);
                terms.add(new ReceivedDateTerm(DateTerm.LE, beforeDate));
                terms.add(new SentDateTerm(DateTerm.LE, beforeDate));

            } else if (value.equals(ATTACHMENT)) {

            } else if (value.equals(UNREAD)) {
                terms.add(new FlagTerm(new Flags(Flag.SEEN), false));
            } else if (value.equals(FLAGGED)) {
                FlagTerm fts[] = new FlagTerm[allFlagStrings.length + 1];
                fts[0] = new FlagTerm(new Flags(Flag.FLAGGED), true);
                for (int i = 0; i < allFlagStrings.length; ++i)
                    fts[i + 1] = new FlagTerm(new Flags(allFlagStrings[i]), true);
                terms.add(new OrTerm(fts));
            } else if (value.equals(TAGGED)) {
                FlagTerm fts[] = new FlagTerm[atags.size()];
                int i = 0;
                for (Tag tag : atags)
                    fts[i++] = new FlagTerm(new Flags(tag.getTagId()), true);
                terms.add(new OrTerm(fts));
            } else if (value.equals(UNANSWERED)) {
                terms.add(new FlagTerm(new Flags(Flag.ANSWERED), false));
            } else if (value.equals(PRIORITY)) {
                HeaderTerm p1 = new HeaderTerm("X-Priority", "1");
                HeaderTerm p2 = new HeaderTerm("X-Priority", "2");
                terms.add(new OrTerm(p1, p2));
            }

        });
    }

    int n = terms.size();
    if (n == 1) {
        searchTerm = terms.get(0);
    } else if (n > 1) {
        SearchTerm vterms[] = new SearchTerm[n];
        terms.toArray(vterms);
        searchTerm = new AndTerm(vterms);
    }
    return searchTerm;
}

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

/**
 * Retrieves new messages from the given folder. This implementation creates a {@link SearchTerm} that searches for
 * all messages in the folder that are {@link javax.mail.Flags.Flag#RECENT RECENT}, not {@link
 * javax.mail.Flags.Flag#ANSWERED ANSWERED}, and not {@link javax.mail.Flags.Flag#DELETED DELETED}. The search term
 * is used to {@link Folder#search(SearchTerm) search} for new messages.
 *
 * @param folder the folder to retrieve new messages from
 * @return the new messages//  ww w. j  av a2  s . c o m
 * @throws MessagingException in case of JavaMail errors
 */
protected Message[] searchForNewMessages(Folder folder) throws MessagingException {
    if (!folder.isOpen()) {
        return new Message[0];
    }
    Flags supportedFlags = folder.getPermanentFlags();
    SearchTerm searchTerm = null;
    if (supportedFlags != null) {
        if (supportedFlags.contains(Flags.Flag.RECENT)) {
            searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
        }
        if (supportedFlags.contains(Flags.Flag.ANSWERED)) {
            FlagTerm answeredTerm = new FlagTerm(new Flags(Flags.Flag.ANSWERED), false);
            if (searchTerm == null) {
                searchTerm = answeredTerm;
            } else {
                searchTerm = new AndTerm(searchTerm, answeredTerm);
            }
        }
        if (supportedFlags.contains(Flags.Flag.DELETED)) {
            FlagTerm deletedTerm = new FlagTerm(new Flags(Flags.Flag.DELETED), false);
            if (searchTerm == null) {
                searchTerm = deletedTerm;
            } else {
                searchTerm = new AndTerm(searchTerm, deletedTerm);
            }
        }
    }
    return searchTerm != null ? folder.search(searchTerm) : folder.getMessages();
}

From source file:org.xwiki.contrib.mail.internal.DefaultMailReader.java

/**
 * {@inheritDoc}//from  ww  w . j  a va2 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 List<Message> read(final String folder, final boolean onlyUnread, final int max)
        throws MessagingException {
    assert (getMailSource() != null);
    assert (getMailSource().getHostname() != null);

    store = null;
    List<Message> messages = new ArrayList<Message>();
    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);

    Message[] msgsArray;
    // Searches for mails not already read
    if (onlyUnread) {
        FlagTerm searchterms = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        msgsArray = fldr.search(searchterms);
    } else {
        msgsArray = fldr.getMessages();
    }

    if (max > 0 && msgsArray.length > max) {
        msgsArray = (Message[]) ArrayUtils.subarray(msgsArray, 0, max);
    }
    messages = new ArrayList<Message>(Arrays.asList(msgsArray));

    logger.info("Found " + messages.size() + " messages");

    // Note: we leave the Store opened to allow reading returned Messages

    return messages;
}

From source file:org.apache.james.jmap.model.MessageFactoryTest.java

@Test
public void headersShouldBeSetIntoMessage() throws Exception {
    String headers = "From: user <user@domain>\n" + "Subject: test subject\n"
            + "To: user1 <user1@domain>, user2 <user2@domain>\n" + "Cc: usercc <usercc@domain>\n"
            + "Bcc: userbcc <userbcc@domain>\n" + "Reply-To: \"user to reply to\" <user.reply.to@domain>\n"
            + "In-Reply-To: <SNT124-W2664003139C1E520CF4F6787D30@phx.gbl>\n"
            + "Other-header: other header value";
    MetaDataWithContent testMail = MetaDataWithContent.builder().uid(2).flags(new Flags(Flag.SEEN))
            .size(headers.length()).internalDate(INTERNAL_DATE)
            .content(new ByteArrayInputStream(headers.getBytes(Charsets.UTF_8))).attachments(ImmutableList.of())
            .mailboxId(MAILBOX_ID).messageId(MessageId.of("user|box|2")).build();

    Emailer user = Emailer.builder().name("user").email("user@domain").build();
    Emailer user1 = Emailer.builder().name("user1").email("user1@domain").build();
    Emailer user2 = Emailer.builder().name("user2").email("user2@domain").build();
    Emailer usercc = Emailer.builder().name("usercc").email("usercc@domain").build();
    Emailer userbcc = Emailer.builder().name("userbcc").email("userbcc@domain").build();
    Emailer userRT = Emailer.builder().name("user to reply to").email("user.reply.to@domain").build();
    ImmutableMap<String, String> headersMap = ImmutableMap.<String, String>builder()
            .put("Cc", "usercc <usercc@domain>").put("Bcc", "userbcc <userbcc@domain>")
            .put("Subject", "test subject").put("From", "user <user@domain>")
            .put("To", "user1 <user1@domain>, user2 <user2@domain>")
            .put("Reply-To", "\"user to reply to\" <user.reply.to@domain>")
            .put("In-Reply-To", "<SNT124-W2664003139C1E520CF4F6787D30@phx.gbl>")
            .put("Other-header", "other header value").put("Date", "Tue, 14 Jul 2015 12:30:42 +0000")
            .put("MIME-Version", "1.0").build();
    Message testee = messageFactory.fromMetaDataWithContent(testMail);
    Message expected = Message.builder().id(MessageId.of("user|box|2")).blobId(BlobId.of("2"))
            .threadId("user|box|2").mailboxIds(ImmutableList.of(MAILBOX_ID))
            .inReplyToMessageId("<SNT124-W2664003139C1E520CF4F6787D30@phx.gbl>").headers(headersMap).from(user)
            .to(ImmutableList.of(user1, user2)).cc(ImmutableList.of(usercc)).bcc(ImmutableList.of(userbcc))
            .replyTo(ImmutableList.of(userRT)).subject("test subject").date(ZONED_DATE).size(headers.length())
            .preview("(Empty)").textBody("").build();
    assertThat(testee).isEqualToComparingFieldByField(expected);
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

public synchronized static Message[] readAll(String protocol, String server, int securityConnection, int port,
        String user, String password, boolean onlyUnreadMessages) {
    Message[] msgs = null;/*  w ww. ja  v  a 2 s . c  o  m*/
    try {
        Properties props = System.getProperties();
        updateSecurityProps(protocol, server, securityConnection, props);
        Session session = Session.getDefaultInstance(props, null);

        if (LOGGER.isDebugEnabled()) {
            session.setDebug(true);
        } else {
            session.setDebug(false);
        }

        // instantiate POP3-store and connect to server
        store = session.getStore(protocol);
        boolean connected = SyncStore.connect(store, protocol, server, port, user, password);
        if (!connected) {
            return msgs;
        }
        connPoint = SyncStore.getConnPoint(store, protocol, server, port, user, password);
        store = connPoint.getStore();

        // access default folder
        folder = store.getDefaultFolder();

        // can't find default folder
        if (folder == null) {
            throw new Exception("No default folder");
        }

        // messages are always in folder INBOX
        folder = folder.getFolder("INBOX");

        // can't find INBOX
        if (folder == null) {
            throw new Exception("No POP3 INBOX");
        }

        // open folder
        folder.open(Folder.READ_WRITE);

        // retrieve messages
        if (onlyUnreadMessages) {
            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            msgs = folder.search(ft);
        } else {
            msgs = folder.getMessages();
        }
    } catch (Exception ex) {
        if (LogThrottle.isReady("MailReader1", 240)) {
            LOGGER.error(ExceptionUtils.getStackTrace(ex));
        }
    }
    return msgs;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public int numCorreosNOL(String name) {
    int numMensa = 0;
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {//from  ww  w  .  j av a  2 s .c o  m
        users u = usuarioService.getByLogin(name);

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

        Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        System.out.println(" " + msg.length);
        numMensa = msg.length;
    } catch (Exception ex) {
    }
    return numMensa;
}