Example usage for javax.mail.internet MimeMessage getRecipients

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

Introduction

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

Prototype

@Override
public Address[] getRecipients(Message.RecipientType type) throws MessagingException 

Source Link

Document

Returns the recepients specified by the type.

Usage

From source file:com.sonicle.webtop.mail.Service.java

public Message reply(MailAccount account, MimeMessage orig, boolean replyToAll, boolean fromSent)
        throws MessagingException {
    MimeMessage reply = new MimeMessage(account.getMailSession());
    /*/*from  w ww .  ja v a  2s . c o  m*/
     * Have to manipulate the raw Subject header so that we don't lose
     * any encoding information.  This is safe because "Re:" isn't
     * internationalized and (generally) isn't encoded.  If the entire
     * Subject header is encoded, prefixing it with "Re: " still leaves
     * a valid and correct encoded header.
     */
    String subject = orig.getHeader("Subject", null);
    if (subject != null) {
        if (!subject.regionMatches(true, 0, "Re: ", 0, 4)) {
            subject = "Re: " + subject;
        }
        reply.setHeader("Subject", subject);
    }
    Address a[] = null;
    if (!fromSent)
        a = orig.getReplyTo();
    else {
        Address ax[] = orig.getRecipients(RecipientType.TO);
        if (ax != null) {
            a = new Address[1];
            a[0] = ax[0];
        }
    }
    reply.setRecipients(Message.RecipientType.TO, a);
    if (replyToAll) {
        Vector v = new Vector();
        Session session = account.getMailSession();
        // add my own address to list
        InternetAddress me = InternetAddress.getLocalAddress(session);
        if (me != null) {
            v.addElement(me);
        }
        // add any alternate names I'm known by
        String alternates = null;
        if (session != null) {
            alternates = session.getProperty("mail.alternates");
        }
        if (alternates != null) {
            eliminateDuplicates(v, InternetAddress.parse(alternates, false));
        }
        // should we Cc all other original recipients?
        String replyallccStr = null;
        boolean replyallcc = false;
        if (session != null) {
            replyallcc = PropUtil.getBooleanSessionProperty(session, "mail.replyallcc", false);
        }
        // add the recipients from the To field so far
        eliminateDuplicates(v, a);
        a = orig.getRecipients(Message.RecipientType.TO);
        a = eliminateDuplicates(v, a);
        if (a != null && a.length > 0) {
            if (replyallcc) {
                reply.addRecipients(Message.RecipientType.CC, a);
            } else {
                reply.addRecipients(Message.RecipientType.TO, a);
            }
        }
        a = orig.getRecipients(Message.RecipientType.CC);
        a = eliminateDuplicates(v, a);
        if (a != null && a.length > 0) {
            reply.addRecipients(Message.RecipientType.CC, a);
        }
        // don't eliminate duplicate newsgroups
        a = orig.getRecipients(MimeMessage.RecipientType.NEWSGROUPS);
        if (a != null && a.length > 0) {
            reply.setRecipients(MimeMessage.RecipientType.NEWSGROUPS, a);
        }
    }

    String msgId = orig.getHeader("Message-Id", null);
    if (msgId != null) {
        reply.setHeader("In-Reply-To", msgId);
    }

    /*
     * Set the References header as described in RFC 2822:
     *
     * The "References:" field will contain the contents of the parent's
     * "References:" field (if any) followed by the contents of the parent's
     * "Message-ID:" field (if any).  If the parent message does not contain
     * a "References:" field but does have an "In-Reply-To:" field
     * containing a single message identifier, then the "References:" field
     * will contain the contents of the parent's "In-Reply-To:" field
     * followed by the contents of the parent's "Message-ID:" field (if
     * any).  If the parent has none of the "References:", "In-Reply-To:",
     * or "Message-ID:" fields, then the new message will have no
     * "References:" field.
     */
    String refs = orig.getHeader("References", " ");
    if (refs == null) {
        // XXX - should only use if it contains a single message identifier
        refs = orig.getHeader("In-Reply-To", " ");
    }
    if (msgId != null) {
        if (refs != null) {
            refs = MimeUtility.unfold(refs) + " " + msgId;
        } else {
            refs = msgId;
        }
    }
    if (refs != null) {
        reply.setHeader("References", MimeUtility.fold(12, refs));
    }

    //try {
    //    setFlags(answeredFlag, true);
    //} catch (MessagingException mex) {
    //    // ignore it
    //}
    return reply;
}

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

/**
 * Fetch a message from a folder.// w  ww.  j  a v  a2 s  .  c  o  m
 * 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.alfresco.email.server.impl.subetha.SubethaEmailMessage.java

private void processMimeMessage(MimeMessage mimeMessage) {
    if (from == null) {
        Address[] addresses = null;/*from ww w  .  j  a  v  a2  s  . co  m*/
        try {
            addresses = mimeMessage.getFrom();
        } catch (MessagingException e) {
            throw new EmailMessageException(ERR_EXTRACTING_FROM_ADDRESS, e.getMessage());
        }
        if (addresses == null || addresses.length == 0) {
            //throw new EmailMessageException(ERR_NO_FROM_ADDRESS);
        } else {
            if (addresses[0] instanceof InternetAddress) {
                from = ((InternetAddress) addresses[0]).getAddress();
            } else {
                from = addresses[0].toString();
            }
        }
    }

    if (to == null) {
        Address[] addresses = null;
        try {
            addresses = mimeMessage.getAllRecipients();
        } catch (MessagingException e) {
            throw new EmailMessageException(ERR_EXTRACTING_TO_ADDRESS, e.getMessage());
        }
        if (addresses == null || addresses.length == 0) {
            //throw new EmailMessageException(ERR_NO_TO_ADDRESS);
        } else {
            if (addresses[0] instanceof InternetAddress) {
                to = ((InternetAddress) addresses[0]).getAddress();
            } else {
                to = addresses[0].toString();
            }
        }
    }

    if (cc == null) {
        try {
            ArrayList<String> list = new ArrayList<String>();

            Address[] cca = mimeMessage.getRecipients(RecipientType.CC);

            if (cca != null) {
                for (Address a : cca) {
                    list.add(a.toString());
                }
            }
            cc = list;
        } catch (MessagingException e) {
            // Do nothing - this is not a show-stopper.
            cc = null;
        }
    }

    try {
        subject = mimeMessage.getSubject();
        //subject = encodeSubject(mimeMessage.getSubject());
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_EXTRACTING_SUBJECT, e.getMessage());
    }
    //if (subject == null)
    //{
    //    subject = ""; // Just anti-null stub :)
    //}

    try {
        sentDate = mimeMessage.getSentDate();
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_EXTRACTING_SENT_DATE, e.getMessage());
    }
    if (sentDate == null) {
        sentDate = new Date(); // Just anti-null stub :)
    }

    parseMessagePart(mimeMessage);
    attachments = new EmailMessagePart[attachmentList.size()];
    attachmentList.toArray(attachments);
    attachmentList = null;
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Extracts properties and text from an EML Document input stream.
 *
 * @param stream/*w  w  w. j  av  a2 s  .c  o m*/
 *            the stream
 * @param handler
 *            the handler
 * @param metadata
 *            the metadata
 * @param context
 *            the context
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();

    Properties props = System.getProperties();
    Session mailSession = Session.getDefaultInstance(props, null);

    try {
        MimeMessage message = new MimeMessage(mailSession, stream);

        String subject = message.getSubject();
        String from = this.convertAddressesToString(message.getFrom());
        // Recipients :
        String messageException = "";
        String to = "";
        String cc = "";
        String bcc = "";
        try {
            // QVIDMS-2004 Added because of bug in Mail Api
            to = this.convertAddressesToString(message.getRecipients(Message.RecipientType.TO));
            cc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.CC));
            bcc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.BCC));
        } catch (AddressException e) {
            e.printStackTrace();
            messageException = e.getRef();
            if (messageException.indexOf("recipients:") != -1) {
                to = messageException.substring(0, messageException.indexOf(":"));
            }
        }
        metadata.set(Office.AUTHOR, from);
        metadata.set(DublinCore.TITLE, subject);
        metadata.set(DublinCore.SUBJECT, subject);

        xhtml.element("h1", subject);

        xhtml.startElement("dl");
        header(xhtml, "From", MimeUtility.decodeText(from));
        header(xhtml, "To", MimeUtility.decodeText(to.toString()));
        header(xhtml, "Cc", MimeUtility.decodeText(cc.toString()));
        header(xhtml, "Bcc", MimeUtility.decodeText(bcc.toString()));

        // // Parse message
        // if (message.getContent() instanceof MimeMultipart) {
        // // Multipart message, call matching method
        // MimeMultipart multipart = (MimeMultipart) message.getContent();
        // this.extractMultipart(xhtml, multipart, context);

        List<String> attachmentList = new ArrayList<String>();
        // prepare attachments
        prepareExtractMultipart(xhtml, message, null, context, attachmentList);
        if (attachmentList.size() > 0) {
            // TODO internationalization
            header(xhtml, "Attachments", attachmentList.toString());
        }
        xhtml.endElement("dl");

        // a supprimer si pb et a remplacer par ce qui est commenT
        adaptedExtractMultipart(xhtml, message, null, context);

        xhtml.endDocument();
    } catch (Exception e) {
        throw new TikaException("Error while processing message", e);
    }
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage verifyHeaders(String subject) throws MessagingException {
    assertThat(fakeMailContext.getSentMails()).containsOnly(new FakeMailContext.SentMail(
            new MailAddress(SIEVE_LOCALHOST), Lists.newArrayList(new MailAddress(USER)), null));
    MimeMessage result = fakeMailContext.getSentMails().get(0).getMsg();
    assertThat(result.getSubject()).isEqualTo(subject);
    assertThat(result.getRecipients(RecipientType.TO)).containsOnly(new InternetAddress(USER));
    return result;
}

From source file:org.apache.nifi.processors.email.ExtractEmailHeaders.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();

    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> processedFlowFilesList = new ArrayList<>();

    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;/*from   ww w .  j a v  a2s. co  m*/
    }

    final List<String> capturedHeadersList = Arrays
            .asList(context.getProperty(CAPTURED_HEADERS).getValue().toLowerCase().split(":"));

    final Map<String, String> attributes = new HashMap<>();
    session.read(originalFlowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream rawIn) throws IOException {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                Properties props = new Properties();
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage originalMessage = new MimeMessage(mailSession, in);
                MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
                // RFC-2822 determines that a message must have a "From:" header
                // if a message lacks the field, it is flagged as invalid
                Address[] from = originalMessage.getFrom();
                Date sentDate = originalMessage.getSentDate();
                if (from == null || sentDate == null) {
                    // Throws MessageException due to lack of minimum required headers
                    throw new MessagingException("Message failed RFC2822 validation");
                } else if (capturedHeadersList.size() > 0) {
                    Enumeration headers = originalMessage.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header header = (Header) headers.nextElement();
                        if (StringUtils.isNotEmpty(header.getValue())
                                && capturedHeadersList.contains(header.getName().toLowerCase())) {
                            attributes.put("email.headers." + header.getName().toLowerCase(),
                                    header.getValue());
                        }
                    }
                }
                if (Array.getLength(originalMessage.getAllRecipients()) > 0) {
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.TO)); toCount++) {
                        attributes.put(EMAIL_HEADER_TO + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.TO)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.BCC)); toCount++) {
                        attributes.put(EMAIL_HEADER_BCC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.BCC)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.CC)); toCount++) {
                        attributes.put(EMAIL_HEADER_CC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.CC)[toCount].toString());
                    }
                }
                // Incredibly enough RFC-2822 specified From as a "mailbox-list" so an array I returned by getFrom
                for (int toCount = 0; toCount < ArrayUtils.getLength(originalMessage.getFrom()); toCount++) {
                    attributes.put(EMAIL_HEADER_FROM + "." + toCount,
                            originalMessage.getFrom()[toCount].toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getMessageID())) {
                    attributes.put(EMAIL_HEADER_MESSAGE_ID, originalMessage.getMessageID());
                }
                if (originalMessage.getReceivedDate() != null) {
                    attributes.put(EMAIL_HEADER_RECV_DATE, originalMessage.getReceivedDate().toString());
                }
                if (originalMessage.getSentDate() != null) {
                    attributes.put(EMAIL_HEADER_SENT_DATE, originalMessage.getSentDate().toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getSubject())) {
                    attributes.put(EMAIL_HEADER_SUBJECT, originalMessage.getSubject());
                }
                // Zeroes EMAIL_ATTACHMENT_COUNT
                attributes.put(EMAIL_ATTACHMENT_COUNT, "0");
                // But insert correct value if attachments are present
                if (parser.hasAttachments()) {
                    attributes.put(EMAIL_ATTACHMENT_COUNT, String.valueOf(parser.getAttachmentList().size()));
                }

            } catch (Exception e) {
                // Message is invalid or triggered an error during parsing
                attributes.clear();
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    if (attributes.size() > 0) {
        FlowFile updatedFlowFile = session.putAllAttributes(originalFlowFile, attributes);
        logger.info("Extracted {} headers into {} file", new Object[] { attributes.size(), updatedFlowFile });
        processedFlowFilesList.add(updatedFlowFile);
    }

    session.transfer(processedFlowFilesList, REL_SUCCESS);
    session.transfer(invalidFlowFilesList, REL_FAILURE);

}

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;/*from  w  w  w  . j a  v a  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;// w  ww  .  ja  v  a2 s.  co  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.craftercms.commons.mail.impl.EmailFactoryImplTest.java

@Test
public void testGetEmailWithBodyParam() throws Exception {
    EmailImpl email = (EmailImpl) emailFactory.getEmail(FROM, TO, CC, BCC, REPLY_TO, SUBJECT, BODY, false);

    assertNotNull(email);/*from w w w  . j av a 2 s . c  om*/

    MimeMessage msg = email.message;

    assertArrayEquals(InternetAddress.parse(FROM), msg.getFrom());
    assertArrayEquals(InternetAddress.parse(StringUtils.join(TO)), msg.getRecipients(Message.RecipientType.TO));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(CC)), msg.getRecipients(Message.RecipientType.CC));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(BCC)),
            msg.getRecipients(Message.RecipientType.BCC));
    assertArrayEquals(InternetAddress.parse(REPLY_TO), msg.getReplyTo());
    assertEquals(SUBJECT, msg.getSubject());
    assertEquals(BODY, msg.getContent());
}

From source file:org.craftercms.commons.mail.impl.EmailFactoryImplTest.java

@Test
public void testGetEmailWithBodyTemplate() throws Exception {
    Map<String, Object> model = Collections.<String, Object>singletonMap("name", "John Doe");
    String body = processTemplate(TEMPLATE_NAME, model);

    EmailImpl email = (EmailImpl) emailFactory.getEmail(FROM, TO, CC, BCC, REPLY_TO, SUBJECT, TEMPLATE_NAME,
            model, false);/*from  ww w. jav a2 s.  c o m*/

    assertNotNull(email);

    MimeMessage msg = email.message;

    assertArrayEquals(InternetAddress.parse(FROM), msg.getFrom());
    assertArrayEquals(InternetAddress.parse(StringUtils.join(TO)), msg.getRecipients(Message.RecipientType.TO));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(CC)), msg.getRecipients(Message.RecipientType.CC));
    assertArrayEquals(InternetAddress.parse(StringUtils.join(BCC)),
            msg.getRecipients(Message.RecipientType.BCC));
    assertArrayEquals(InternetAddress.parse(REPLY_TO), msg.getReplyTo());
    assertEquals(SUBJECT, msg.getSubject());
    assertEquals(body, msg.getContent());
}