Example usage for javax.mail.internet MimeMessage getFrom

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

Introduction

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

Prototype

@Override
public Address[] getFrom() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "From" header fields.

Usage

From source file:org.silverpeas.core.mail.SmtpMailSendingTest.java

private void assertMailSent(MailToSend verifiedMailToSend, GreenMailOperations mail) throws Exception {
    assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(),
            hasSize(1));/* w  w w  . java  2 s  . com*/

    assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO));

    MimeMessage[] messages = mail.getReceivedMessages();
    assertThat(messages, arrayWithSize(1));

    MimeMessage sentMessage = messages[0];
    MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next();

    assertThat(sentMessage.getFrom().length, is(1));
    assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0];
    assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
    assertThat(internetAddressFrom.getPersonal(),
            is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));

    assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1));
    assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressTo = (InternetAddress) sentMessage
            .getRecipients(Message.RecipientType.TO)[0];
    assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail()));
    assertThat(internetAddressTo.getPersonal(), nullValue());

    assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject()));
    if (verifiedMailToSend.getContent().getValue() instanceof Multipart) {
        assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass()));
    } else {
        assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""),
                is(verifiedMailToSend.getContent().getValue()));
    }

    assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date()));

    assertThat(sentMessage.getReplyTo().length, is(1));
    if (verifiedMailToSend.isReplyToRequired()) {
        assertThat(sentMessage.getHeader("Reply-To"), notNullValue());
        assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class));
        InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0];
        assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
        assertThat(internetAddressReplyTo.getPersonal(),
                is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));
    } else {
        assertThat(sentMessage.getHeader("Reply-To"), nullValue());
        assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString()));
    }
}

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

/**
 * When we send out an email with just a text body, et expect to get a
 * Multipart email having only a plain text body.
 *//*from   w w w . j  a v a  2s  .c om*/
@Test
public void testSimpleEmail() throws Exception {
    // Given:
    EmailService service = makeALocalMailer();

    InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones");
    String expectedSubject = "This is a Test Email";
    String expectedTextBody = "This is a simple test.";

    // When:
    service.sendSimpleEmail(expectedTo, expectedSubject, expectedTextBody);

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());

    WiserMessage message = messages.get(0);
    assertNotNull("No message was actually sent.", message);
    MimeMessage mimeMessage = message.getMimeMessage();
    Address[] toRecipients = mimeMessage.getRecipients(RecipientType.TO);
    assertEquals("Number of To: Recipient;", 1, toRecipients.length);
    Address toRecipient = toRecipients[0];
    assertEquals("To: Recipient;", expectedTo, toRecipient);

    InternetAddress expectedFrom = new InternetAddress("admin@domain.com", "Domain Admin");
    Address[] fromArr = mimeMessage.getFrom();
    assertEquals("From: email addresses;", 1, fromArr.length);
    assertEquals("Email From: address,", expectedFrom, fromArr[0]);

    assertEquals("Subject;", expectedSubject, mimeMessage.getSubject());

    assertNotNull("The date of the email cannot be null.", mimeMessage.getSentDate());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 1, body.getCount());
    MimeMultipart textPart = ((MimeMultipart) body.getBodyPart(0).getContent());
    assertEquals("Number of MIME parts in the text body;", 1, textPart.getCount());
    MimeBodyPart plainTextPart = ((MimeBodyPart) textPart.getBodyPart(0));
    assertTrue("Expected the plain text content to be text/plain.", plainTextPart.isMimeType("text/plain"));
    assertEquals("Text Body;", expectedTextBody, plainTextPart.getContent());
}

From source file:com.riq.MailHandlerServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)

        throws IOException {

    log.info("Inside MailServlet doPost");

    // TODO get path information to determine target Department for this email

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {/*from  ww  w.jav  a  2s.  c  o m*/

        MimeMessage msg = new MimeMessage(session, req.getInputStream());
        Address sender = msg.getFrom()[0];
        Address replyTo = msg.getReplyTo()[0];

        //      DEBUG
        //       log.info("Message Class: " + msg.getClass());
        //       log.info("Message Stream: " + msg.getInputStream());
        //       log.info("Message RawStream: " + msg.getRawInputStream());
        //       log.info("Message Flags: " + msg.getFlags());
        //       log.info("Message Content: " + msg.getContent().toString());
        //       log.info("Message ContentID: " + msg.getContentID());
        //       log.info("Message ContentMD: " + msg.getContentMD5());
        //       log.info("Message ContentType: " + msg.getContentType());
        //       log.info("Message Description: " + msg.getDescription());
        //       log.info("Message Disposition: " + msg.getDisposition());
        //       log.info("Message Encoding: " + msg.getEncoding());
        //       log.info("Message Filename: " + msg.getFileName());
        //       log.info("Message Line Count: " + msg.getLineCount());
        //       log.info("Message ID: " + msg.getMessageID());
        //       log.info("Message Number: " + msg.getMessageNumber());
        //       log.info("Message Size: " + msg.getSize());
        //       log.info("Message Subject: " + msg.getSubject());
        //       log.info("Message RawInputStream: " + msg.getRawInputStream().toString());
        //       log.info("Message ReplyTo: " + replyTo);
        //       log.info("Message Sender: " + sender.toString());
        //       log.info("Request URL TO: " +  getServletContext());      

        String alertMsgString = getText(msg);

        alertMsgString = alertMsgString.replaceAll("Begin forwarded message:", "");
        alertMsgString = alertMsgString.replaceAll("Forwarded message", "");
        alertMsgString = alertMsgString.replaceAll("Dispatch@co.morris.nj.us", "");
        alertMsgString = alertMsgString.replaceAll("Date:", "");
        alertMsgString = alertMsgString.replaceAll(">", "");
        alertMsgString = alertMsgString.replaceAll("::", "-");
        alertMsgString = alertMsgString.replaceAll("< ", "");
        alertMsgString = alertMsgString.replaceAll("----------", "");
        alertMsgString = alertMsgString.replaceAll("Subject:", "");
        alertMsgString = alertMsgString.replaceAll("To:", "");
        alertMsgString = alertMsgString.replaceAll("From:", "");

        //  Added to grab gmail confirmations
        //  alertMsgString = alertMsgString.substring(50, 300);

        try {

            String queryDept = "select from " + Department.class.getName() +
            // TODO: johnreilly workaround for getting allRecipients... 
            // " where dispatchId == '" + toAddressDigitsOnly + "' " + 
                    " where dispatchId == '2599' " + " && fromEmail == '" + sender + "' ";
            log.info("queryDept: " + queryDept);
            List<Department> depts = (List<Department>) pm.newQuery(queryDept).execute();

            if (depts.size() != 0) {

                for (Department d : depts) {

                    // need to filter further e.g. last two hours
                    String queryAlert = "select from " + Alert.class.getName() + " where deptId == "
                            + depts.get(0).getid() + " && messageId == '" + msg.getMessageID() + "' ";
                    log.info("queryAlert: " + queryAlert);
                    List<Alert> alerts = (List<Alert>) pm.newQuery(queryAlert).execute();
                    log.info("queryAlert Result Qty: " + alerts.size());

                    if (alerts.size() == 0) {

                        riqGeocode(alertMsgString);

                        // geocode the address from the Alert
                        Map<String, String> geoResults = riqGeocode(alertMsgString);
                        log.info("lat print: " + geoResults.get("lat"));
                        log.info("lng print: " + geoResults.get("lng"));

                        // create the alert
                        Long deptId = depts.get(0).getid();
                        Long timeStamp = System.currentTimeMillis();
                        Alert a = new Alert(deptId, timeStamp, alertMsgString.trim(), sender.toString(),
                                "Active", "", geoResults.get("lat"), geoResults.get("lng"), msg.getMessageID());
                        pm.makePersistent(a);

                        // query to get id of this alert
                        String queryThisAlert = "select from " + Alert.class.getName() + " where deptId == "
                                + deptId + " " + " && timeStamp == " + timeStamp;
                        log.info("queryThisAlert: " + queryThisAlert);
                        List<Alert> thisAlert = (List<Alert>) pm.newQuery(queryThisAlert).execute();
                        log.info("queryCurrentAlert Result Qty: " + thisAlert.size());

                        // create Tracking records for "special" Locations
                        String querySpecialLocs = "select from " + Location.class.getName()
                                + " where special == 'yes' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + querySpecialLocs);
                        List<Location> specialLocs = (List<Location>) pm.newQuery(querySpecialLocs).execute();
                        log.info("querySpecialLocs qty: " + specialLocs.size());

                        for (Location specL : specialLocs) {
                            Tracking tSL = new Tracking(deptId, thisAlert.get(0).getid(), specL.getid(),
                                    System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                    "location", specL.getid(), null, "autoAddLocation");
                            pm.makePersistent(tSL);
                        }

                        // search Dept for Location where distant Members presumed not to be responding are set
                        String queryFarawayLocs = "select from " + Location.class.getName()
                                + " where vru == '2' && deptId == " + deptId;
                        log.info("querySpecialLocs: " + queryFarawayLocs);
                        List<Location> farawayLoc = (List<Location>) pm.newQuery(queryFarawayLocs).execute();
                        log.info("queryFarawayLocs qty: " + farawayLoc.size());

                        // create Tracking records for Members presumed not to be responder due to fresh ETA
                        String queryFarAwayResponders = "select from " + Member.class.getName()
                                + " where distGroup == '4' ";
                        log.info("queryFarAwayResponders: " + queryFarAwayResponders);
                        List<Member> farawayMembers = (List<Member>) pm.newQuery(queryFarAwayResponders)
                                .execute();
                        log.info("queryFarAwayResponders qty: " + farawayMembers.size());

                        if (farawayMembers.size() != 0) {
                            for (Member far : farawayMembers) {
                                Tracking tMFAR = new Tracking(deptId, thisAlert.get(0).getid(),
                                        farawayLoc.get(0).getid(), System.currentTimeMillis(), null, // TODO: johnreilly authorId tbd
                                        "farawayAddMember", far.getid(), null, responseType);
                                pm.makePersistent(tMFAR);
                            }
                        }

                        // TODO: testing restriction HACKER - remove at launch
                        // send alert email
                        String queryMember = "select from " + Member.class.getName() + " where deptId == "
                                + deptId + " && type == 'Hacker' ";
                        List<Member> members = (List<Member>) pm.newQuery(queryMember).execute();

                        //TODO Geocode address to insure easy navigation
                        //TODO johnreilly: add street and town fields to Alert
                        msg.setFrom(
                                new InternetAddress("admin@responderiq05.appspotmail.com", "FirstResponder"));
                        msg.setSubject("Alert!");
                        msg.setText(" Y=" + d.getinboundVRU1() + "&N=" + d.getinboundVRU2() +
                        // "&3=" + d.getinboundVRU3() +  
                                "&A=" + thisAlert.get(0).getalertMsgString());

                        // send message to all dept members who permit tracking (and sending email alerts)
                        for (Member m : members) {
                            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m.getsmsAddress(),
                                    m.getfirstName() + "" + m.getlastName()));
                            log.info("Member: " + m.getsmsAddress() + "|" + m.getlastName());
                        }
                    }
                    // only process for one department - should only be one department
                    break;
                }
            }
        } catch (MessagingException me) {
            log.info("Error: Messaging");
        } catch (IndexOutOfBoundsException mi) {
            log.info("Error: Out of Bounds");
        }

        // Do not send alert notification if email is a Google Confirmation
        //      if (! sender.toString().contains("mail-noreply@google.com")) {
        //        Transport.send(msg);
        //      }

    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } finally {
        pm.close();
    }

}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessage() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTest", ".eml");

    outputFile.deleteOnExit();//from ww w .j a v a2 s.  c om

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessage(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessageRaw() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTestRaw", ".eml");

    outputFile.deleteOnExit();/*ww w  .  j  av  a 2 s.c o  m*/

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessageRaw(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

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

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();
    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;//from   w  w w  .  ja v  a  2s.  co  m
    }
    final List<FlowFile> attachmentsList = new ArrayList<>();
    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> originalFlowFilesList = new ArrayList<>();

    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");
                }
                originalFlowFilesList.add(originalFlowFile);
                if (parser.hasAttachments()) {
                    final String originalFlowFileName = originalFlowFile
                            .getAttribute(CoreAttributes.FILENAME.key());
                    try {
                        for (final DataSource data : parser.getAttachmentList()) {
                            FlowFile split = session.create(originalFlowFile);
                            final Map<String, String> attributes = new HashMap<>();
                            if (StringUtils.isNotBlank(data.getName())) {
                                attributes.put(CoreAttributes.FILENAME.key(), data.getName());
                            }
                            if (StringUtils.isNotBlank(data.getContentType())) {
                                attributes.put(CoreAttributes.MIME_TYPE.key(), data.getContentType());
                            }
                            String parentUuid = originalFlowFile.getAttribute(CoreAttributes.UUID.key());
                            attributes.put(ATTACHMENT_ORIGINAL_UUID, parentUuid);
                            attributes.put(ATTACHMENT_ORIGINAL_FILENAME, originalFlowFileName);
                            split = session.append(split, new OutputStreamCallback() {
                                @Override
                                public void process(OutputStream out) throws IOException {
                                    IOUtils.copy(data.getInputStream(), out);
                                }
                            });
                            split = session.putAllAttributes(split, attributes);
                            attachmentsList.add(split);
                        }
                    } catch (FlowFileHandlingException e) {
                        // Something went wrong
                        // Removing splits that may have been created
                        session.remove(attachmentsList);
                        // Removing the original flow from its list
                        originalFlowFilesList.remove(originalFlowFile);
                        logger.error(
                                "Flowfile {} triggered error {} while processing message removing generated FlowFiles from sessions",
                                new Object[] { originalFlowFile, e });
                        invalidFlowFilesList.add(originalFlowFile);
                    }
                }
            } catch (Exception e) {
                // Another error hit...
                // Removing the original flow from its list
                originalFlowFilesList.remove(originalFlowFile);
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                // Message is invalid or triggered an error during parsing
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    session.transfer(attachmentsList, REL_ATTACHMENTS);

    // As per above code, originalFlowfile may be routed to invalid or
    // original depending on RFC2822 compliance.
    session.transfer(invalidFlowFilesList, REL_FAILURE);
    session.transfer(originalFlowFilesList, REL_ORIGINAL);

    if (attachmentsList.size() > 10) {
        logger.info("Split {} into {} files", new Object[] { originalFlowFile, attachmentsList.size() });
    } else if (attachmentsList.size() > 1) {
        logger.info("Split {} into {} files: {}",
                new Object[] { originalFlowFile, attachmentsList.size(), attachmentsList });
    }
}

From source file:mitm.application.djigzo.james.mailets.Relay.java

private MailAddress getFrom(MimeMessage message) throws MessagingException {
    Address[] froms = message.getFrom();

    if (froms == null || froms.length == 0) {
        return null;
    }/*from   w  ww  . jav  a2  s  .  com*/

    return new MailAddress(EmailAddressUtils.getEmailAddress(froms[0]));
}

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 ww  .j ava  2 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:com.angstoverseer.service.mail.MailServiceImpl.java

@Override
public void handleIncomingEmail(InputStream inputStream) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {//from  w w w. j  a v a  2  s . c  o  m
        MimeMessage mimeMessage = new MimeMessage(session, inputStream);

        Object messageContent = mimeMessage.getContent();
        String message;
        if (messageContent instanceof Multipart) {
            Multipart mp = (Multipart) messageContent;
            BodyPart bodyPart = mp.getBodyPart(0);
            InputStream is = bodyPart.getInputStream();
            message = convertStreamToString(is);
        } else {
            message = (String) messageContent;
        }

        Address sender = mimeMessage.getFrom()[0];
        final String commandOutput = commandService.process(message, extractEmail(sender.toString()));

        sendResponseMail(sender, commandOutput, mimeMessage.getSubject());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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 av  a  2 s. 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);

}