Example usage for javax.mail.internet MimeMessage getAllHeaders

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

Introduction

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

Prototype

@Override
public Enumeration<Header> getAllHeaders() throws MessagingException 

Source Link

Document

Return all the headers from this Message as an enumeration of Header objects.

Usage

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from  w ww  .j  a  va 2  s  .  c o m
 *
 * @param mime DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
public static int getMessageSize(MimeMessage mime) {
    int size = 0;

    Enumeration e = null;

    try {
        e = mime.getAllHeaders();

        while (e.hasMoreElements()) {
            size += ((Header) e.nextElement()).toString().length();
        }
    } catch (MessagingException me) {
    }

    size += getPartSize(mime);

    return size;
}

From source file: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
 * (and now I guess in many JTrac installations worldwide)
 * for quite a while now, on Tomcat without any problems.  This helps a lot
 * especially when the SMTP server is slow to respond, etc.
 *//*from www .j ava 2 s .  c o m*/
private void sendInNewThread(final MimeMessage message) {
    new Thread() {
        @Override
        public void run() {
            logger.debug("send mail thread start");

            // major: nested try catch. It's really ugly.
            // It appears to be caused by getAllHeaders that is throwing
            // a MessagingException.
            try {
                try {
                    sender.send(message);
                    logger.debug("send mail thread successfull");
                } catch (Exception e) {
                    logger.error("send mail thread failed", e);
                    logger.error("mail headers dump start");
                    Enumeration headers = message.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header h = (Header) headers.nextElement();
                        logger.info(h.getName() + ": " + h.getValue());
                    }
                    logger.error("mail headers dump end");
                }
                // major: why propagating a RuntimeException in a thread?
                // It's going to be swallowed in its own thread of execution
                // No one will see it. Also, this is a duplicated catch.
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }.start();
}

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.
 *//*www.  j a va  2 s . co 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:org.alfresco.repo.imap.ImapServiceImpl.java

@SuppressWarnings("unchecked")
public void persistMessageHeaders(NodeRef messageRef, MimeMessage message) {
    try {/*w w  w.j av a  2  s . c om*/
        Enumeration<Header> headers = message.getAllHeaders();
        List<String> messaheHeadersProperties = new ArrayList<String>();
        while (headers.hasMoreElements()) {
            Header header = headers.nextElement();
            if (isPersistableHeader(header)) {
                messaheHeadersProperties.add(
                        header.getName() + ImapModel.MESSAGE_HEADER_TO_PERSIST_SPLITTER + header.getValue());

                if (logger.isDebugEnabled()) {
                    logger.debug("[persistHeaders] Persisting Header " + header.getName() + " : "
                            + header.getValue());
                }
            }
        }

        Map<QName, Serializable> props = new HashMap<QName, Serializable>();
        props.put(ImapModel.PROP_MESSAGE_HEADERS, (Serializable) messaheHeadersProperties);

        serviceRegistry.getNodeService().addAspect(messageRef, ImapModel.ASPECT_IMAP_MESSAGE_HEADERS, props);
    } catch (MessagingException me) {

    }
}

From source file:org.apache.camel.component.james.smtp.SMTPTest.java

/**
 * Test send matching message./*  w  w w  . ja va2  s. co  m*/
 * 
 * @throws Exception
 *             the exception
 */
@SuppressWarnings("unchecked")
@Test
public void testSendMatchingMessage() throws Exception {
    String sender = "sender@localhost";
    String rcpt = "rcpt@localhost";
    String body = "Subject: test\r\n\r\nTestmail";
    SMTPClient client = new SMTPClient();
    client.connect("localhost", port);
    client.helo("localhost");
    client.setSender(sender);
    client.addRecipient(rcpt);

    client.sendShortMessageData(body);
    client.quit();
    client.disconnect();
    resultEndpoint.expectedMessageCount(1);
    resultEndpoint.expectedBodyReceived().body(InputStream.class);
    Exchange ex = resultEndpoint.getReceivedExchanges().get(0);
    Map<String, Object> headers = ex.getIn().getHeaders();
    assertEquals(sender, headers.get(MailEnvelopeMessage.SMTP_SENDER_ADRRESS));
    assertEquals(rcpt, headers.get(MailEnvelopeMessage.SMTP_RCPT_ADRRESS_LIST));

    // check type converter
    MimeMessage message = ex.getIn().getBody(MimeMessage.class);
    Enumeration<Header> mHeaders = message.getAllHeaders();
    Header header = null;
    while (mHeaders.hasMoreElements()) {
        header = mHeaders.nextElement();
        if (header.getName().equals("Subject")) {
            break;
        }
    }
    assertNotNull(header);
    assertEquals("Subject", header.getName());
    assertEquals(header.getValue(), "test");

    resultEndpoint.assertIsSatisfied();
}

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

protected MessageDetails mimeToDetails(MimeMessage message, String folderName, long uid)
        throws IOException, MessagingException, UnsupportedEncodingException {
    MessageDetails mDetails = new MessageDetails();

    Object con = message.getContent();

    StringBuffer sbPlain = new StringBuffer();
    ArrayList<MessageAttachment> attachmentList = new ArrayList<MessageAttachment>();

    boolean isHTML = handleParts(message, con, sbPlain, attachmentList);

    System.out.println(isHTML);//from  w  w  w  . j  av a  2 s.c  o  m

    if (isHTML) {
        mDetails.setText(filterHtmlDocument(sbPlain.toString(), folderName, uid));
    } else {
        mDetails.setText(txtDocumentToHtml(sbPlain.toString(), folderName, uid));
    }

    mDetails.setMessageAttachments(attachmentList);

    mDetails.setRawHeader(message.getAllHeaders().toString());

    return mDetails;
}

From source file:org.apache.james.jdkim.mailets.DKIMSign.java

@SuppressWarnings("unchecked")
private void prependHeader(MimeMessage message, String signatureHeader) throws MessagingException {
    List<String> prevHeader = new LinkedList<String>();
    // read all the headers
    for (Enumeration<String> e = message.getAllHeaderLines(); e.hasMoreElements();) {
        String headerLine = e.nextElement();
        prevHeader.add(headerLine);/*from   www.j a  v  a  2s.co m*/
    }
    // remove all the headers
    for (Enumeration<Header> e = message.getAllHeaders(); e.hasMoreElements();) {
        Header header = e.nextElement();
        message.removeHeader(header.getName());
    }
    // add our header
    message.addHeaderLine(signatureHeader);
    // add the remaining headers using "addHeaderLine" that won't alter the
    // insertion order.
    for (Iterator<String> i = prevHeader.iterator(); i.hasNext();) {
        String header = i.next();
        message.addHeaderLine(header);
    }
}

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   w w  w  .ja  va 2s.  c o 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);

}