Example usage for javax.mail Header getValue

List of usage examples for javax.mail Header getValue

Introduction

In this page you can find the example usage for javax.mail Header getValue.

Prototype

public String getValue() 

Source Link

Document

Returns the value of this header.

Usage

From source file:edu.stanford.muse.email.EmailFetcherStats.java

/**
 * this method returns the text content of the message as a list of strings
 * // each element of the list could be the content of a multipart message
 * // m is the top level subject//from ww  w  . jav a 2s  . c  om
 * // p is the specific part that we are processing (p could be == m)
 * also sets up names of attachments (though it will not download the
 * attachment unless downloadAttachments is true)
 */
private List<String> processMessagePart(int messageNum, Message m, Part p, List<Blob> attachmentsList)
        throws MessagingException, IOException {
    List<String> list = new ArrayList<String>(); // return list
    if (p == null) {
        dataErrors.add("part is null: " + folder_name() + " idx " + messageNum);
        return list;
    }

    if (p == m && p.isMimeType("text/html")) {
        /*
        String s = "top level part is html! message:" + m.getSubject() + " " + m.getDescription();
        dataErrors.add(s);
        */
        // we don't normally expect the top-level part to have content-type text/html
        // but we saw this happen on some sample archives pst -> emailchemy. so allow it and handle it by parsing the html
        String html = (String) p.getContent();
        String text = Util.unescapeHTML(html);
        org.jsoup.nodes.Document doc = Jsoup.parse(text);

        StringBuilder sb = new StringBuilder();
        HTMLUtils.extractTextFromHTML(doc.body(), sb);
        list.add(sb.toString());
        return list;
    }

    if (p.isMimeType("text/plain")) {
        //make sure, p is not wrongly labelled as plain text.
        Enumeration headers = p.getAllHeaders();
        boolean dirty = false;
        if (headers != null)
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                String name = h.getName();
                String value = h.getValue();
                if (name != null && value != null) {
                    if (name.equals("Content-transfer-encoding") && value.equals("base64")) {
                        dirty = true;
                        break;
                    }
                }
            }
        String fname = p.getFileName();
        if (fname != null) {
            int idx = fname.lastIndexOf('.');
            if ((idx < fname.length()) && (idx >= 0)) {
                String extension = fname.substring(idx);
                //anything extension other than .txt is suspicious.
                if (!extension.equals(".txt"))
                    dirty = true;
            }
        }
        if (dirty) {
            dataErrors.add("Dirty message part, has conflicting message part headers." + folder_name()
                    + " Message# " + messageNum);
            return list;
        }

        log.debug("Message part with content type text/plain");
        String content;
        String type = p.getContentType(); // new InputStreamReader(p.getInputStream(), "UTF-8");
        try {
            // if forced encoding is set, we read the string with that encoding, otherwise we just use whatever p.getContent gives us
            if (FORCED_ENCODING != null) {
                byte b[] = Util.getBytesFromStream(p.getInputStream());
                content = new String(b, FORCED_ENCODING);
            } else
                content = (String) p.getContent();
        } catch (UnsupportedEncodingException uee) {
            dataErrors.add("Unsupported encoding: " + folder_name() + " Message #" + messageNum + " type "
                    + type + ", using brute force conversion");
            // a particularly nasty issue:javamail can't handle utf-7 encoding which is common with hotmail and exchange servers.
            // we're using the workaround suggested on this page: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4304013
            // though it may be better to consider official support for utf-7 or other encodings.

            // TOFIX: I get an exception for utfutf8-encoding which has a base64 encoding embedded on it.
            // Unsupported encoding: gmail-sent Message #10477 type text/plain; charset=x-utf8utf8; name="newyorker.txt",
            // the hack below doesn't work for it.
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            p.writeTo(bao);
            content = bao.toString();
        }
        list.add(content);
    } else if (p.isMimeType("multipart/*") || p.isMimeType("message/rfc822")) {
        // rfc822 mime type is for embedded mbox format or some such (appears for things like
        // forwarded messages). the content appears to be just a multipart.
        Object o = p.getContent();
        if (o instanceof Multipart) {
            Multipart allParts = (Multipart) o;
            if (p.isMimeType("multipart/alternative")) {
                // this is an alternative mime type. v common case to have text and html alternatives
                // so just process the text part if there is one, and avoid fetching the alternatives.
                // useful esp. because many ordinary messages are alternative: text and html and we don't want to fetch the html.
                // revisit in future we want to retain the html alternative for display purposes
                Part[] parts = new Part[allParts.getCount()];
                for (int i = 0; i < parts.length; i++)
                    parts[i] = allParts.getBodyPart(i);

                for (int i = 0; i < parts.length; i++) {
                    Part thisPart = parts[i];
                    if (thisPart.isMimeType("text/plain")) {
                        // common case, return quickly
                        list.add((String) thisPart.getContent());
                        log.debug("Multipart/alternative with content type text/plain");
                        return list;
                    }
                }

                // no text part, let's look for an html part. this happens for html parts.
                for (int i = 0; i < allParts.getCount(); i++) {
                    Part thisPart = parts[i];
                    if (thisPart.isMimeType("text/html")) {
                        // common case, return quickly
                        String html = (String) thisPart.getContent();
                        String text = Util.unescapeHTML(html);
                        org.jsoup.nodes.Document doc = Jsoup.parse(text);

                        StringBuilder sb = new StringBuilder();
                        HTMLUtils.extractTextFromHTML(doc.body(), sb);
                        list.add(sb.toString());

                        log.debug("Multipart/alternative with content type text/html");
                        return list;
                    }
                }

                // no text or html part. hmmm... blindly process the first part only
                if (allParts.getCount() >= 1)
                    list.addAll(processMessagePart(messageNum, m, allParts.getBodyPart(0), attachmentsList));
            } else {
                // process it like a regular multipart
                for (int i = 0; i < allParts.getCount(); i++) {
                    BodyPart bp = allParts.getBodyPart(i);
                    list.addAll(processMessagePart(messageNum, m, bp, attachmentsList));
                }
            }
        } else if (o instanceof Part)
            list.addAll(processMessagePart(messageNum, m, (Part) o, attachmentsList));
        else
            dataErrors.add("Unhandled part content, " + folder_name() + " Message #" + messageNum
                    + "Java type: " + o.getClass() + " Content-Type: " + p.getContentType());
    } else {
        try {
            // do attachments only if downloadAttachments is set.
            // some apps do not need attachments, so this saves some time.
            // however, it seems like a lot of time is taken in imap prefetch, which gets attachments too?
            if (fetchConfig.downloadAttachments)
                handleAttachments(messageNum, m, p, list, attachmentsList);
        } catch (Exception e) {
            dataErrors.add("Ignoring attachment for " + folder_name() + " Message #" + messageNum + ": "
                    + Util.stackTrace(e));
        }
    }

    return list;
}

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

public void processGetSource(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String foldername = request.getParameter("folder");
    String uid = request.getParameter("id");
    String sheaders = request.getParameter("headers");
    boolean headers = sheaders.equals("true");
    String sout = null;/*from ww w .  ja  va2s. co m*/
    try {
        account.checkStoreConnected();
        //StringBuffer sb = new StringBuffer("<pre>");
        StringBuffer sb = new StringBuffer();
        FolderCache mcache = account.getFolderCache(foldername);
        Message msg = mcache.getMessage(Long.parseLong(uid));
        //Folder folder=msg.getFolder();
        for (Enumeration e = msg.getAllHeaders(); e.hasMoreElements();) {
            Header header = (Header) e.nextElement();
            //sb.append(MailUtils.htmlescape(header.getName()) + ": " + MailUtils.htmlescape(header.getValue()) + "\n");
            sb.append(header.getName() + ": " + header.getValue() + "\n");
        }
        if (!headers) {
            BufferedReader br = new BufferedReader(new InputStreamReader(msg.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null) {
                //sb.append(MailUtils.htmlescape(line) + "\n");
                sb.append(line + "\n");
            }
        }
        //sb.append("</pre>");
        sout = "{\nresult: true, source: '" + StringEscapeUtils.escapeEcmaScript(sb.toString()) + "'\n}";
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
    }
    out.println(sout);
}

From source file:org.alfresco.repo.imap.ImapServiceImpl.java

@SuppressWarnings("unchecked")
public void persistMessageHeaders(NodeRef messageRef, MimeMessage message) {
    try {//www .  j av a2 s. c  o  m
        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.axiom.attachments.impl.AbstractPart.java

public String getHeader(String name) {
    String key = name.toLowerCase();
    Header header = (Header) headers.get(key);
    String value = header == null ? null : header.getValue();
    if (log.isDebugEnabled()) {
        log.debug("getHeader name=(" + name + ") value=(" + value + ")");
    }// w  w  w .  j a  va  2s. co m
    return value;
}

From source file:org.apache.axis.attachments.MimeUtils.java

/**
 * Gets the header length for any part.// www.  java  2 s  .  co  m
 * @param bp the part to determine the header length for.
 * @return the length in bytes.
 *
 * @throws javax.mail.MessagingException
 * @throws java.io.IOException
 */
private static long getHeaderLength(javax.mail.internet.MimeBodyPart bp)
        throws javax.mail.MessagingException, java.io.IOException {

    javax.mail.internet.MimeBodyPart headersOnly = new javax.mail.internet.MimeBodyPart(
            new javax.mail.internet.InternetHeaders(), new byte[0]);

    for (java.util.Enumeration en = bp.getAllHeaders(); en.hasMoreElements();) {
        javax.mail.Header header = (javax.mail.Header) en.nextElement();

        headersOnly.addHeader(header.getName(), header.getValue());
    }

    java.io.ByteArrayOutputStream bas = new java.io.ByteArrayOutputStream(1024 * 16);

    headersOnly.writeTo(bas);
    bas.close();

    return (long) bas.size(); // This has header length plus the crlf part that seperates the data
}

From source file:org.apache.axis.attachments.MultiPartRelatedInputStream.java

/**
 * Create a new Multipart stream.// ww  w.ja  va2 s.  c o m
 * @param contentType  the string that holds the contentType
 * @param stream       the true input stream from where the source
 *
 * @throws org.apache.axis.AxisFault if the stream could not be created
 */
public MultiPartRelatedInputStream(String contentType, java.io.InputStream stream)
        throws org.apache.axis.AxisFault {

    super(null); // don't cache this stream.

    if (!(stream instanceof BufferedInputStream)) {
        stream = new BufferedInputStream(stream);
    }

    try {

        // First find the start and boundary parameters. There are real weird rules regard what
        // can be in real headers what needs to be escaped etc  let mail parse it.
        javax.mail.internet.ContentType ct = new javax.mail.internet.ContentType(contentType);
        String rootPartContentId = ct.getParameter("start"); // Get the root part content.

        if (rootPartContentId != null) {
            rootPartContentId = rootPartContentId.trim();

            if (rootPartContentId.startsWith("<")) {
                rootPartContentId = rootPartContentId.substring(1);
            }

            if (rootPartContentId.endsWith(">")) {
                rootPartContentId = rootPartContentId.substring(0, rootPartContentId.length() - 1);
            }

        }

        if (ct.getParameter("boundary") != null) {
            String boundaryStr = "--" + ct.getParameter("boundary"); // The boundary with -- add as always the case.

            // if start is null then the first attachment is the rootpart
            // First read the start boundary -- this is done with brute force since the servlet may swallow the crlf between headers.
            // after this we use the more efficient boundarydelimeted stream.  There should never be any data here anyway.
            byte[][] boundaryMarker = new byte[2][boundaryStr.length() + 2];

            IOUtils.readFully(stream, boundaryMarker[0]);

            boundary = (boundaryStr + "\r\n").getBytes("US-ASCII");

            int current = 0;

            // This just goes brute force one byte at a time to find the first boundary.
            // in most cases this just a crlf.
            for (boolean found = false; !found; ++current) {
                if (!(found = java.util.Arrays.equals(boundaryMarker[current & 0x1], boundary))) {
                    System.arraycopy(boundaryMarker[current & 0x1], 1, boundaryMarker[(current + 1) & 0x1], 0,
                            boundaryMarker[0].length - 1);

                    if (stream.read(boundaryMarker[(current + 1) & 0x1], boundaryMarker[0].length - 1, 1) < 1) {
                        throw new org.apache.axis.AxisFault(
                                Messages.getMessage("mimeErrorNoBoundary", new String(boundary)));
                    }
                }
            }

            // after the first boundary each boundary will have a cr lf at the beginning since after the data in any part there
            // is a cr lf added to put the boundary at the begining of a line.
            boundaryStr = "\r\n" + boundaryStr;
            boundary = boundaryStr.getBytes("US-ASCII");
        } else {
            // Since boundary is not specified, we try to find one.
            for (boolean found = false; !found;) {
                boundary = readLine(stream);
                if (boundary == null)
                    throw new org.apache.axis.AxisFault(Messages.getMessage("mimeErrorNoBoundary", "--"));
                found = boundary.length > 4 && boundary[2] == '-' && boundary[3] == '-';
            }
        }

        // create the boundary delmited stream.
        boundaryDelimitedStream = new org.apache.axis.attachments.BoundaryDelimitedStream(stream, boundary,
                1024);

        // Now read through all potential streams until we have found the root part.
        String contentTransferEncoding = null;

        do {
            contentId = null;
            contentLocation = null;
            contentTransferEncoding = null;

            // Read this attachments headers from the stream.
            javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders(
                    boundaryDelimitedStream);

            // Use java mail utility to read through the headers.
            contentId = headers.getHeader(HTTPConstants.HEADER_CONTENT_ID, null);

            // Clean up the headers and remove any < >
            if (contentId != null) {
                contentId = contentId.trim();

                if (contentId.startsWith("<")) {
                    contentId = contentId.substring(1);
                }

                if (contentId.endsWith(">")) {
                    contentId = contentId.substring(0, contentId.length() - 1);
                }

                contentId = contentId.trim();

                //  if (!contentId.startsWith("cid:")) {
                //      contentId =
                //              "cid:"
                //              + contentId;        // make sure its identified as cid
                //  }
            }

            contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null);

            if (contentLocation != null) {
                contentLocation = contentLocation.trim();

                if (contentLocation.startsWith("<")) {
                    contentLocation = contentLocation.substring(1);
                }

                if (contentLocation.endsWith(">")) {
                    contentLocation = contentLocation.substring(0, contentLocation.length() - 1);
                }

                contentLocation = contentLocation.trim();
            }

            contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null);

            if (contentType != null) {
                contentType = contentType.trim();
            }

            contentTransferEncoding = headers.getHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, null);

            if (contentTransferEncoding != null) {
                contentTransferEncoding = contentTransferEncoding.trim();
            }

            java.io.InputStream decodedStream = boundaryDelimitedStream;

            if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) {
                decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding);
            }

            if ((rootPartContentId != null) && !rootPartContentId.equals(contentId)) { // This is a part that has come in prior to the root part. Need to buffer it up.
                javax.activation.DataHandler dh = new javax.activation.DataHandler(
                        new org.apache.axis.attachments.ManagedMemoryDataSource(decodedStream, MAX_CACHED,
                                contentType, true));
                AttachmentPart ap = new AttachmentPart(dh);

                if (contentId != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId);
                }

                if (contentLocation != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation);
                }

                for (java.util.Enumeration en = headers.getNonMatchingHeaders(
                        new String[] { HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION,
                                HTTPConstants.HEADER_CONTENT_TYPE }); en.hasMoreElements();) {
                    javax.mail.Header header = (javax.mail.Header) en.nextElement();
                    String name = header.getName();
                    String value = header.getValue();

                    if ((name != null) && (value != null)) {
                        name = name.trim();

                        if (name.length() != 0) {
                            ap.addMimeHeader(name, value);
                        }
                    }
                }

                addPart(contentId, contentLocation, ap);

                boundaryDelimitedStream = boundaryDelimitedStream.getNextStream(); // Gets the next stream.
            }
        } while ((null != boundaryDelimitedStream) && (rootPartContentId != null)
                && !rootPartContentId.equals(contentId));

        if (boundaryDelimitedStream == null) {
            throw new org.apache.axis.AxisFault(Messages.getMessage("noRoot", rootPartContentId));
        }

        soapStreamBDS = boundaryDelimitedStream;

        if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) {
            soapStream = MimeUtility.decode(boundaryDelimitedStream, contentTransferEncoding);
        } else {
            soapStream = boundaryDelimitedStream; // This should be the SOAP part
        }

        // Read from the input stream all attachments prior to the root part.
    } catch (javax.mail.internet.ParseException e) {
        throw new org.apache.axis.AxisFault(Messages.getMessage("mimeErrorParsing", e.getMessage()));
    } catch (java.io.IOException e) {
        throw new org.apache.axis.AxisFault(Messages.getMessage("readError", e.getMessage()));
    } catch (javax.mail.MessagingException e) {
        throw new org.apache.axis.AxisFault(Messages.getMessage("readError", e.getMessage()));
    }
}

From source file:org.apache.axis.attachments.MultiPartRelatedInputStream.java

/**
 * This will read streams in till the one that is needed is found.
 *
 * @param id id is the stream being sought.
 *
 * @return the part for the id/*from w w w.j  a v  a 2  s. c o  m*/
 *
 * @throws org.apache.axis.AxisFault
 */
protected Part readTillFound(final String[] id) throws org.apache.axis.AxisFault {

    if (boundaryDelimitedStream == null) {
        return null; // The whole stream has been consumed already
    }

    Part ret = null;

    try {
        if (soapStreamBDS == boundaryDelimitedStream) { // Still on the SOAP stream.
            if (!eos) { // The SOAP packet has not been fully read yet. Need to store it away.
                java.io.ByteArrayOutputStream soapdata = new java.io.ByteArrayOutputStream(1024 * 8);
                byte[] buf = new byte[1024 * 16];
                int byteread = 0;

                do {
                    byteread = soapStream.read(buf);

                    if (byteread > 0) {
                        soapdata.write(buf, 0, byteread);
                    }
                } while (byteread > -1);

                soapdata.close();

                soapStream = new java.io.ByteArrayInputStream(soapdata.toByteArray());
            }

            boundaryDelimitedStream = boundaryDelimitedStream.getNextStream();
        }

        // Now start searching for the data.
        if (null != boundaryDelimitedStream) {
            do {
                String contentType = null;
                String contentId = null;
                String contentTransferEncoding = null;
                String contentLocation = null;

                // Read this attachments headers from the stream.
                javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders(
                        boundaryDelimitedStream);

                contentId = headers.getHeader("Content-Id", null);

                if (contentId != null) {
                    contentId = contentId.trim();

                    if (contentId.startsWith("<")) {
                        contentId = contentId.substring(1);
                    }

                    if (contentId.endsWith(">")) {
                        contentId = contentId.substring(0, contentId.length() - 1);
                    }

                    //   if (!contentId.startsWith("cid:")) {
                    //       contentId = "cid:" + contentId;
                    //   }

                    contentId = contentId.trim();
                }

                contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null);

                if (contentType != null) {
                    contentType = contentType.trim();
                }

                contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null);

                if (contentLocation != null) {
                    contentLocation = contentLocation.trim();
                }

                contentTransferEncoding = headers.getHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING,
                        null);

                if (contentTransferEncoding != null) {
                    contentTransferEncoding = contentTransferEncoding.trim();
                }

                java.io.InputStream decodedStream = boundaryDelimitedStream;

                if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) {
                    decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding);
                }

                ManagedMemoryDataSource source = new ManagedMemoryDataSource(decodedStream,
                        ManagedMemoryDataSource.MAX_MEMORY_DISK_CACHED, contentType, true);
                DataHandler dh = new DataHandler(source);
                AttachmentPart ap = new AttachmentPart(dh);

                if (contentId != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId);
                }

                if (contentLocation != null) {
                    ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation);
                }

                for (java.util.Enumeration en = headers.getNonMatchingHeaders(
                        new String[] { HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION,
                                HTTPConstants.HEADER_CONTENT_TYPE }); en.hasMoreElements();) {
                    javax.mail.Header header = (javax.mail.Header) en.nextElement();
                    String name = header.getName();
                    String value = header.getValue();

                    if ((name != null) && (value != null)) {
                        name = name.trim();

                        if (name.length() != 0) {
                            ap.addMimeHeader(name, value);
                        }
                    }
                }

                addPart(contentId, contentLocation, ap);

                for (int i = id.length - 1; (ret == null) && (i > -1); --i) {
                    if ((contentId != null) && id[i].equals(contentId)) { // This is the part being sought
                        ret = ap;
                    } else if ((contentLocation != null) && id[i].equals(contentLocation)) {
                        ret = ap;
                    }
                }

                boundaryDelimitedStream = boundaryDelimitedStream.getNextStream();
            } while ((null == ret) && (null != boundaryDelimitedStream));
        }
    } catch (Exception e) {
        throw org.apache.axis.AxisFault.makeFault(e);
    }

    return ret;
}

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

/**
 * Test send matching message./*  w ww. j  a  v  a  2  s .c o 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.camel.component.mail.MailBinding.java

protected Map<String, Object> extractHeadersFromMail(Message mailMessage, Exchange exchange)
        throws MessagingException {
    Map<String, Object> answer = new HashMap<String, Object>();
    Enumeration names = mailMessage.getAllHeaders();

    while (names.hasMoreElements()) {
        Header header = (Header) names.nextElement();
        String value = header.getValue();
        if (headerFilterStrategy != null
                && !headerFilterStrategy.applyFilterToExternalHeaders(header.getName(), value, exchange)) {
            CollectionHelper.appendValue(answer, header.getName(), value);
        }//from   w w  w . j a v  a  2 s. c o  m
    }

    return answer;
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

/**
 * {@inheritDoc}//from   www  .  j  a  va  2s .  c o m
 */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    boolean isOK = false; // Did sample succeed?
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();

    parent.setSampleLabel(getName());

    String samplerString = toString();
    parent.setSamplerData(samplerString);

    /*
     * Perform the sampling
     */
    parent.sampleStart(); // Start timing
    try {
        // Create empty properties
        Properties props = new Properties();

        if (isUseStartTLS()) {
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$
            }
        }

        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: "
                        + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  "
                        + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: "
                            + truststore.getAbsolutePath()
                            + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : "
                            + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ 
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        }

        // Get session
        Session session = Session.getInstance(props, null);

        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());

        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }

        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        parent.setContentType("text/plain"); // $NON-NLS-1$

        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();

            cdata.append("Message "); // $NON-NLS-1$
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);

            final String contentType = message.getContentType();
            child.setContentType(contentType);// Store the content-type
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default
            child.setEncodingAndType(contentType);// Parse the content-type

            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                child.setResponseData(bout.toByteArray()); // Save raw message
                child.setDataType(SampleResult.TEXT);
            } else {
                @SuppressWarnings("unchecked") // Javadoc for the API says this is OK
                Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                        // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }

            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }

        // Close connection
        folder.close(true);
        store.close();

        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$
    } finally {
        busy = false;
    }

    if (parent.getEndTime() == 0) {// not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}