Example usage for javax.mail.internet MimeMessage getFlags

List of usage examples for javax.mail.internet MimeMessage getFlags

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage getFlags.

Prototype

@Override
public synchronized Flags getFlags() throws MessagingException 

Source Link

Document

Return a Flags object containing the flags for this message.

Usage

From source file:Main.java

private static boolean isSeen(MimeMessage msg) throws MessagingException {
    return msg.getFlags().contains(Flags.Flag.SEEN);
}

From source file:Main.java

public static boolean isSeen(MimeMessage msg) throws MessagingException {
    return msg.getFlags().contains(Flags.Flag.SEEN);
}

From source file:populate.java

/**
 * Copy message from src to dst. If dontPreserveFlags is set we first copy the
 * messages to memory, clear all the flags, and then copy to the destination.
 *///from  w w w  .j a  v a2 s .c om
private static void copyMessages(Folder src, Folder dst) throws MessagingException {
    Message[] msgs = src.getMessages();
    if (dontPreserveFlags) {
        for (int i = 0; i < msgs.length; i++) {
            MimeMessage m = new MimeMessage((MimeMessage) msgs[i]);
            m.setFlags(m.getFlags(), false);
            msgs[i] = m;
        }
    }
    src.copyMessages(msgs, dst);
}

From source file:populate.java

/**
 * Copy message from src to dst.  If dontPreserveFlags is set
 * we first copy the messages to memory, clear all the flags,
 * and then copy to the destination.//from   w  w w  .  j  a va2 s  .  co  m
 */
private static void copyMessages(Folder src, Folder dst) throws MessagingException {
    Message[] msgs = src.getMessages();
    if (dontPreserveFlags) {
        for (int i = 0; i < msgs.length; i++) {
            MimeMessage m = new MimeMessage((MimeMessage) msgs[i]);
            m.setFlags(m.getFlags(), false);
            msgs[i] = m;
        }
    }
    if (warn) {
        // have to copy messages one at a time
        for (int i = 0; i < msgs.length; i++) {
            try {
                src.copyMessages(new Message[] { msgs[i] }, dst);
            } catch (MessagingException mex) {
                System.out.println("WARNING: Copy of message " + (i + 1) + " from " + src.getFullName() + " to "
                        + dst.getFullName() + " failed: " + mex.toString());
            }
        }
    } else
        src.copyMessages(msgs, dst);
}

From source file:gr.abiss.calipso.mail.MailSender.java

/**
 * we bend the rules a little and fire off a new thread for sending
 * an email message.  This has the advantage of not slowing down the item
 * create and update screens, i.e. the system returns the next screen
 * after "submit" without blocking.  This has been used in production
 * for quite a while now, on Tomcat without any problems.  This helps a lot
 * especially when the SMTP server is slow to respond, etc.
 */// ww w.j a  v a  2 s.c o  m
private void sendInNewThread(final MimeMessage message) {
    //       try {
    //          logger.info("Sending message: " + message.getSubject() + "\n" + message.getContent());
    //      } catch (MessagingException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      } catch (IOException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      }
    if (logger.isDebugEnabled()) {
        try {
            logger.debug("Message contenttype: " + message.getContentType());
            logger.debug("Message content: " + message.getContent());
            Enumeration headers = message.getAllHeaders();

            logger.debug("Message Headers...");
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                logger.error(h.getName() + ": " + h.getValue());
            }
            logger.debug("Message flags: " + message.getFlags());
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    new Thread() {
        @Override
        public void run() {
            logger.debug("send mail thread start");
            try {
                try {
                    sender.send(message);
                    logger.debug("send mail thread successfull");
                } catch (Exception e) {
                    logger.error("send mail thread failed, dumping headers: ");
                    logger.error("mail headers dump start");
                    Enumeration headers = message.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header h = (Header) headers.nextElement();
                        logger.error(h.getName() + ": " + h.getValue());
                    }
                    logger.error("mail headers dump end, exception follows", e);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }.start();
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder./*from w  ww  .  j a v a2  s .  c  om*/
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}

From source file:org.apache.james.core.MimeMessageWrapper.java

public MimeMessageWrapper(MimeMessage original) throws MessagingException {
    this(Session.getDefaultInstance(System.getProperties()));
    flags = original.getFlags();

    if (source == null) {
        InputStream in;/*  w ww  .j  av  a2 s . c  o m*/

        boolean useMemoryCopy = false;
        String memoryCopy = System.getProperty(USE_MEMORY_COPY);
        if (memoryCopy != null) {
            useMemoryCopy = Boolean.valueOf(memoryCopy);
        }
        try {

            if (useMemoryCopy) {
                ByteArrayOutputStream bos;
                int size = original.getSize();
                if (size > 0) {
                    bos = new ByteArrayOutputStream(size);
                } else {
                    bos = new ByteArrayOutputStream();
                }
                original.writeTo(bos);
                bos.close();
                in = new SharedByteArrayInputStream(bos.toByteArray());
                parse(in);
                in.close();
                saved = true;
            } else {
                MimeMessageInputStreamSource src = new MimeMessageInputStreamSource(
                        "MailCopy-" + UUID.randomUUID().toString());
                OutputStream out = src.getWritableOutputStream();
                original.writeTo(out);
                out.close();
                source = src;
            }

        } catch (IOException ex) {
            // should never happen, but just in case...
            throw new MessagingException("IOException while copying message", ex);
        }
    }
}

From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java

private boolean addEnvelopToDocument(Part part, Map<String, Object> row) throws MessagingException {
    MimeMessage mail = (MimeMessage) part;
    Address[] adresses;/*w  w w  .j  ava 2 s .c  o m*/
    if ((adresses = mail.getFrom()) != null && adresses.length > 0) {
        String from = adresses[0].toString();
        // check if we should ignore this sender
        for (String ignore : this.ignoreFrom) {
            if (from.toLowerCase().contains(ignore)) {
                LOG.info("Ignoring email from " + from);
                return false;
            }
        }
        row.put(FROM, from);
        row.put(FROM_CLEAN, cleanAddress(from));
    } else {
        return false;
    }

    List<String> to = new ArrayList<String>();
    if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) {
        addAddressToList(adresses, to);
    }
    if (!to.isEmpty()) {
        row.put(TO_CC_BCC, to);
        List<String> cleanAddresses = cleanAddresses(to);
        row.put(TO_CC_BCC_CLEAN, cleanAddresses);
        // save first TO address into separate field
        row.put(TO, to.get(0));
        row.put(TO_CLEAN, cleanAddresses.get(0));
    }

    row.put(MESSAGE_ID, mail.getMessageID());
    row.put(SUBJECT, mail.getSubject());

    {
        Date d = mail.getSentDate();
        if (d != null) {
            row.put(SENT_DATE, d);
        }
    }
    {
        Date d = mail.getReceivedDate();
        if (d != null) {
            row.put(RECEIVED_DATE, d);
        }
    }

    List<String> flags = new ArrayList<String>();
    for (Flags.Flag flag : mail.getFlags().getSystemFlags()) {
        if (flag == Flags.Flag.ANSWERED) {
            flags.add(FLAG_ANSWERED);
        } else if (flag == Flags.Flag.DELETED) {
            flags.add(FLAG_DELETED);
        } else if (flag == Flags.Flag.DRAFT) {
            flags.add(FLAG_DRAFT);
        } else if (flag == Flags.Flag.FLAGGED) {
            flags.add(FLAG_FLAGGED);
        } else if (flag == Flags.Flag.RECENT) {
            flags.add(FLAG_RECENT);
        } else if (flag == Flags.Flag.SEEN) {
            flags.add(FLAG_SEEN);
        }
    }
    flags.addAll(Arrays.asList(mail.getFlags().getUserFlags()));
    row.put(FLAGS, flags);

    String[] hdrs = mail.getHeader("X-Mailer");
    if (hdrs != null) {
        row.put(XMAILER, hdrs[0]);
    }
    return true;
}

From source file:org.apache.solr.handler.dataimport.GmailServiceUserMailEntityProcessor.java

private boolean addEnvelopToDocument(Part part, Map<String, Object> row) throws MessagingException {
    MimeMessage mail = (MimeMessage) part;
    Address[] adresses;//ww w. j a v a 2 s  . c om
    if ((adresses = mail.getFrom()) != null && adresses.length > 0) {
        String from = adresses[0].toString();
        // check if we should ignore this sender
        for (String ignore : this.ignoreFrom) {
            if (from.toLowerCase().contains(ignore)) {
                LOG.info("Ignoring email from " + from);
                return false;
            }
        }
        row.put(FROM, from);
        row.put(FROM_CLEAN, cleanAddress(from));
    } else {
        return false;
    }

    List<String> to = new ArrayList<String>();
    if ((adresses = mail.getRecipients(Message.RecipientType.TO)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.CC)) != null) {
        addAddressToList(adresses, to);
    }
    if ((adresses = mail.getRecipients(Message.RecipientType.BCC)) != null) {
        addAddressToList(adresses, to);
    }
    if (!to.isEmpty()) {
        row.put(TO_CC_BCC, to);
        List<String> cleanAddresses = cleanAddresses(to);
        row.put(TO_CC_BCC_CLEAN, cleanAddresses);

        // save first TO address into separate field
        row.put(TO, to.get(0));
        row.put(TO_CLEAN, cleanAddresses.get(0));
    }

    row.put(MESSAGE_ID, mail.getMessageID());
    row.put(SUBJECT, mail.getSubject());

    {
        Date d = mail.getSentDate();
        if (d != null) {
            row.put(SENT_DATE, d);
        }
    }
    {
        Date d = mail.getReceivedDate();
        if (d != null) {
            row.put(RECEIVED_DATE, d);
        }
    }

    List<String> flags = new ArrayList<String>();
    for (Flags.Flag flag : mail.getFlags().getSystemFlags()) {
        if (flag == Flags.Flag.ANSWERED) {
            flags.add(FLAG_ANSWERED);
        } else if (flag == Flags.Flag.DELETED) {
            flags.add(FLAG_DELETED);
        } else if (flag == Flags.Flag.DRAFT) {
            flags.add(FLAG_DRAFT);
        } else if (flag == Flags.Flag.FLAGGED) {
            flags.add(FLAG_FLAGGED);
        } else if (flag == Flags.Flag.RECENT) {
            flags.add(FLAG_RECENT);
        } else if (flag == Flags.Flag.SEEN) {
            flags.add(FLAG_SEEN);
        }
    }
    flags.addAll(Arrays.asList(mail.getFlags().getUserFlags()));
    row.put(FLAGS, flags);

    String[] hdrs = mail.getHeader("X-Mailer");
    if (hdrs != null) {
        row.put(XMAILER, hdrs[0]);
    }
    return true;
}

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

@SuppressWarnings("resource")
@Test/*from  www . j a va  2s .  com*/
@Ignore
public void testMessageHistory() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

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

    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 -> {
        DirectFieldAccessor accessor = new DirectFieldAccessor((invocation.getMock()));
        IMAPFolder folder = mock(IMAPFolder.class);
        accessor.setPropertyValue("folder", folder);
        given(folder.hasNewMessages()).willReturn(true);
        return null;
    }).given(receiver).openFolder();

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

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

    PollableChannel channel = context.getBean("channel", PollableChannel.class);

    adapter.start();
    org.springframework.messaging.Message<?> replMessage = channel.receive(10000);
    MessageHistory history = MessageHistory.read(replMessage);
    assertNotNull(history);
    Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "simpleAdapter", 0);
    assertNotNull(componentHistoryRecord);
    assertEquals("mail:imap-idle-channel-adapter", componentHistoryRecord.get("type"));
    adapter.stop();
    context.close();
}