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.pentaho.di.job.entries.getpop.MailConnection.java

public void setFlagTermNotFlagged() {
    addSearchTerm(new FlagTerm(new Flags(Flags.Flag.FLAGGED), false));
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

public void setFlagTermDraft() {
    addSearchTerm(new FlagTerm(new Flags(Flags.Flag.DRAFT), true));
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

public void setFlagTermNotDraft() {
    addSearchTerm(new FlagTerm(new Flags(Flags.Flag.DRAFT), false));
}

From source file:com.ikon.util.MailUtils.java

/**
 * Import messages/* www.  j av  a  2  s .  c  o m*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info(i + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType());
            log.info("Received: " + msg.getReceivedDate());
            log.info("Sent: " + msg.getSentDate());
            log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() });
            com.ikon.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@Test
public void testIdleChannelAdapterException() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

    //ImapMailReceiver receiver = (ImapMailReceiver) TestUtils.getPropertyValue(adapter, "mailReceiver");

    DirectChannel channel = new DirectChannel();
    channel.subscribe(new AbstractReplyProducingMessageHandler() {

        @Override//  w  ww  . ja v a  2s . com
        protected Object handleRequestMessage(org.springframework.messaging.Message<?> requestMessage) {
            throw new RuntimeException("Failed");
        }
    });
    adapter.setOutputChannel(channel);
    QueueChannel errorChannel = new QueueChannel();
    adapter.setErrorChannel(errorChannel);

    AbstractMailReceiver receiver = new ImapMailReceiver();
    receiver = spy(receiver);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();

    Field folderField = AbstractMailReceiver.class.getDeclaredField("folder");
    folderField.setAccessible(true);
    Folder folder = mock(IMAPFolder.class);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER));
    folderField.set(receiver, folder);

    willAnswer(invocation -> true).given(folder).isOpen();

    willAnswer(invocation -> null).given(receiver).openFolder();

    DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter);
    adapterAccessor.setPropertyValue("mailReceiver", receiver);

    MimeMessage mailMessage = mock(MimeMessage.class);
    Flags flags = mock(Flags.class);
    given(mailMessage.getFlags()).willReturn(flags);
    final Message[] messages = new Message[] { mailMessage };

    willAnswer(invocation -> messages).given(receiver).searchForNewMessages();

    willAnswer(invocation -> null).given(receiver).fetchMessages(messages);

    adapter.start();
    org.springframework.messaging.Message<?> replMessage = errorChannel.receive(10000);
    assertNotNull(replMessage);
    assertEquals("Failed", ((Exception) replMessage.getPayload()).getCause().getMessage());
    adapter.stop();
    context.close();
}

From source file:com.openkm.util.MailUtils.java

/**
 * Import messages/*from  w w  w .  j a v a2  s  . c om*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info("======= ======= {} ======= =======", i);
            log.info("Subject: {}", msg.getSubject());
            log.info("From: {}", msg.getFrom());
            log.info("Received: {}", msg.getReceivedDate());
            log.info("Sent: {}", msg.getSentDate());
            com.openkm.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:org.apache.james.mailbox.store.mail.model.MessageIdMapperTest.java

@Test
public void setFlagsShouldReturnUpdatedFlagsWhenMessageIsInTwoMailboxes() throws Exception {
    message1.setUid(mapperProvider.generateMessageUid());
    message1.setModSeq(mapperProvider.generateModSeq(benwaInboxMailbox));
    sut.save(message1);//from  w w w.  j  ava 2 s .c  o  m

    SimpleMailboxMessage message1InOtherMailbox = SimpleMailboxMessage.copy(benwaWorkMailbox.getMailboxId(),
            message1);
    message1InOtherMailbox.setUid(mapperProvider.generateMessageUid());
    message1InOtherMailbox.setModSeq(mapperProvider.generateModSeq(benwaWorkMailbox));
    sut.save(message1InOtherMailbox);

    MessageId messageId = message1.getMessageId();
    Flags newFlags = new Flags(Flag.ANSWERED);
    Map<MailboxId, UpdatedFlags> flags = sut.setFlags(messageId,
            ImmutableList.of(message1.getMailboxId(), message1InOtherMailbox.getMailboxId()), newFlags,
            FlagsUpdateMode.ADD);

    long modSeqBenwaInboxMailbox = mapperProvider.highestModSeq(benwaInboxMailbox);
    long modSeqBenwaWorkMailbox = mapperProvider.highestModSeq(benwaWorkMailbox);
    UpdatedFlags expectedUpdatedFlags = UpdatedFlags.builder().uid(message1.getUid())
            .modSeq(modSeqBenwaInboxMailbox).oldFlags(new Flags()).newFlags(newFlags).build();
    UpdatedFlags expectedUpdatedFlags2 = UpdatedFlags.builder().uid(message1InOtherMailbox.getUid())
            .modSeq(modSeqBenwaWorkMailbox).oldFlags(new Flags()).newFlags(newFlags).build();
    assertThat(flags).containsOnly(MapEntry.entry(benwaInboxMailbox.getMailboxId(), expectedUpdatedFlags),
            MapEntry.entry(message1InOtherMailbox.getMailboxId(), expectedUpdatedFlags2));
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

@Override
public boolean setMessageReadStatus(MailStoreConfiguration config, String[] uuids, boolean read) {
    Authenticator auth = credentialsProvider.getAuthenticator();
    Folder inbox = null;/* ww w.java  2s  .c  o m*/
    try {
        // Retrieve user's inbox
        Session session = openMailSession(config, auth);
        inbox = getUserInbox(session, config.getInboxFolderName());

        // Verify that we can even perform this operation log info if it isn't capable of operation
        if (!(inbox instanceof UIDFolder)) {
            String msg = "Toggle unread feature is supported only for UIDFolder instances";
            log.info(msg);
            return false;
        }

        inbox.open(Folder.READ_WRITE);

        Message[] msgs = ((UIDFolder) inbox).getMessagesByUID(getMessageUidsAsLong(uuids));
        inbox.setFlags(msgs, new Flags(Flag.SEEN), read);

        return true; // Indicate success

    } catch (MessagingException e) {
        log.error("Messaging exception while deleting messages", e);
    } finally {
        if (inbox != null) {
            try {
                inbox.close(false);
            } catch (Exception e) {
                log.warn("Can't close correctly javamail inbox connection");
            }
            try {
                inbox.getStore().close();
            } catch (Exception e) {
                log.warn("Can't close correctly javamail store connection");
            }
        }
    }

    return false; // We failed if we reached this point
}

From source file:org.apache.james.mailbox.store.mail.model.MessageIdMapperTest.java

@Test
public void setFlagsShouldUpdateFlagsWhenMessageIsInOneMailbox() throws Exception {
    message1.setUid(mapperProvider.generateMessageUid());
    message1.setModSeq(mapperProvider.generateModSeq(benwaInboxMailbox));
    sut.save(message1);/*from   w  w  w. ja  v a2s.  c o  m*/

    MessageId messageId = message1.getMessageId();
    sut.setFlags(messageId, ImmutableList.of(message1.getMailboxId()), new Flags(Flag.ANSWERED),
            FlagsUpdateMode.ADD);

    List<MailboxMessage> messages = sut.find(ImmutableList.of(messageId), MessageMapper.FetchType.Body);
    assertThat(messages).hasSize(1);
    assertThat(messages.get(0).isAnswered()).isTrue();
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@SuppressWarnings("resource")
@Test/*  w w  w .  j ava2s.co  m*/
public void testNoInitialIdleDelayWhenRecentNotSupported() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);

    ImapMailReceiver receiver = new ImapMailReceiver("imap:foo");
    receiver = spy(receiver);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();

    final IMAPFolder folder = mock(IMAPFolder.class);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER));
    given(folder.isOpen()).willReturn(false).willReturn(true);
    given(folder.exists()).willReturn(true);

    DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter);
    adapterAccessor.setPropertyValue("mailReceiver", receiver);

    Field storeField = AbstractMailReceiver.class.getDeclaredField("store");
    storeField.setAccessible(true);
    Store store = mock(Store.class);
    given(store.isConnected()).willReturn(true);
    given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder);
    storeField.set(receiver, store);

    willAnswer(invocation -> folder).given(receiver).getFolder();

    MimeMessage mailMessage = mock(MimeMessage.class);
    Flags flags = mock(Flags.class);
    given(mailMessage.getFlags()).willReturn(flags);
    final Message[] messages = new Message[] { mailMessage };

    final AtomicInteger shouldFindMessagesCounter = new AtomicInteger(2);
    willAnswer(invocation -> {
        /*
         * Return the message from first invocation of waitForMessages()
         * and in receive(); then return false in the next call to
         * waitForMessages() so we enter idle(); counter will be reset
         * to 1 in the mocked idle().
         */
        if (shouldFindMessagesCounter.decrementAndGet() >= 0) {
            return messages;
        } else {
            return new Message[0];
        }
    }).given(receiver).searchForNewMessages();

    willAnswer(invocation -> null).given(receiver).fetchMessages(messages);

    willAnswer(invocation -> {
        Thread.sleep(5000);
        shouldFindMessagesCounter.set(1);
        return null;
    }).given(folder).idle();

    adapter.start();

    /*
     * Idle takes 5 seconds; if all is well, we should receive the first message
     * before then.
     */
    assertNotNull(channel.receive(3000));
    // We should not receive any more until the next idle elapses
    assertNull(channel.receive(3000));
    assertNotNull(channel.receive(6000));
    adapter.stop();
    context.close();
}