Example usage for javax.mail.internet MimeMessage getInputStream

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

Introduction

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

Prototype

@Override
public InputStream getInputStream() throws IOException, MessagingException 

Source Link

Document

Return a decoded input stream for this Message's "content".

Usage

From source file:nl.nn.adapterframework.http.HttpSender.java

protected void addMtomMultiPartToPostMethod(PostMethod hmethod, String message, ParameterValueList parameters,
        ParameterResolutionContext prc) throws SenderException, MessagingException, IOException {
    MyMimeMultipart mimeMultipart = new MyMimeMultipart("related");
    String start = null;/*  w w w .j  a  v a  2 s.c o  m*/
    if (StringUtils.isNotEmpty(getInputMessageParam())) {
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(message, "application/xop+xml; charset=UTF-8; type=\"text/xml\"");
        start = "<" + getInputMessageParam() + ">";
        mimeBodyPart.setContentID(start);
        ;
        mimeMultipart.addBodyPart(mimeBodyPart);
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "appended (string)part [" + getInputMessageParam() + "] with value ["
                    + message + "]");
    }
    if (parameters != null) {
        for (int i = 0; i < parameters.size(); i++) {
            ParameterValue pv = parameters.getParameterValue(i);
            String paramType = pv.getDefinition().getType();
            String name = pv.getDefinition().getName();
            if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
                Object value = pv.getValue();
                if (value instanceof FileInputStream) {
                    FileInputStream fis = (FileInputStream) value;
                    String fileName = null;
                    String sessionKey = pv.getDefinition().getSessionKey();
                    if (sessionKey != null) {
                        fileName = (String) prc.getSession().get(sessionKey + "Name");
                    }
                    MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary");
                    mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT);
                    ByteArrayDataSource ds = new ByteArrayDataSource(fis, "application/octet-stream");
                    mimeBodyPart.setDataHandler(new DataHandler(ds));
                    mimeBodyPart.setFileName(fileName);
                    mimeBodyPart.setContentID("<" + name + ">");
                    mimeMultipart.addBodyPart(mimeBodyPart);
                    if (log.isDebugEnabled())
                        log.debug(getLogPrefix() + "appended (file)part [" + name + "] with value [" + value
                                + "] and name [" + fileName + "]");
                } else {
                    throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                            + "] for parameter [" + name + "]");
                }
            } else {
                String value = pv.asStringValue("");
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                mimeBodyPart.setContent(value, "text/xml");
                if (start == null) {
                    start = "<" + name + ">";
                    mimeBodyPart.setContentID(start);
                } else {
                    mimeBodyPart.setContentID("<" + name + ">");
                }
                mimeMultipart.addBodyPart(mimeBodyPart);
                if (log.isDebugEnabled())
                    log.debug(
                            getLogPrefix() + "appended (string)part [" + name + "] with value [" + value + "]");
            }
        }
    }
    if (StringUtils.isNotEmpty(getMultipartXmlSessionKey())) {
        String multipartXml = (String) prc.getSession().get(getMultipartXmlSessionKey());
        if (StringUtils.isEmpty(multipartXml)) {
            log.warn(getLogPrefix() + "sessionKey [" + getMultipartXmlSessionKey() + "] is empty");
        } else {
            Element partsElement;
            try {
                partsElement = XmlUtils.buildElement(multipartXml);
            } catch (DomBuilderException e) {
                throw new SenderException(getLogPrefix() + "error building multipart xml", e);
            }
            Collection parts = XmlUtils.getChildTags(partsElement, "part");
            if (parts == null || parts.size() == 0) {
                log.warn(getLogPrefix() + "no part(s) in multipart xml [" + multipartXml + "]");
            } else {
                int c = 0;
                Iterator iter = parts.iterator();
                while (iter.hasNext()) {
                    c++;
                    Element partElement = (Element) iter.next();
                    //String partType = partElement.getAttribute("type");
                    String partName = partElement.getAttribute("name");
                    String partMimeType = partElement.getAttribute("mimeType");
                    String partSessionKey = partElement.getAttribute("sessionKey");
                    Object partObject = prc.getSession().get(partSessionKey);
                    if (partObject instanceof FileInputStream) {
                        FileInputStream fis = (FileInputStream) partObject;
                        MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary");
                        mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT);
                        ByteArrayDataSource ds = new ByteArrayDataSource(fis,
                                (partMimeType == null ? "application/octet-stream" : partMimeType));
                        mimeBodyPart.setDataHandler(new DataHandler(ds));
                        mimeBodyPart.setFileName(partName);
                        mimeBodyPart.setContentID("<" + partName + ">");
                        mimeMultipart.addBodyPart(mimeBodyPart);
                        if (log.isDebugEnabled())
                            log.debug(getLogPrefix() + "appended (file)part [" + partSessionKey
                                    + "]  with value [" + partObject + "] and name [" + partName + "]");
                    } else {
                        String partValue = (String) prc.getSession().get(partSessionKey);
                        MimeBodyPart mimeBodyPart = new MimeBodyPart();
                        mimeBodyPart.setContent(partValue, "text/xml");
                        if (start == null) {
                            start = "<" + partName + ">";
                            mimeBodyPart.setContentID(start);
                        } else {
                            mimeBodyPart.setContentID("<" + partName + ">");
                        }
                        mimeMultipart.addBodyPart(mimeBodyPart);
                        if (log.isDebugEnabled())
                            log.debug(getLogPrefix() + "appended (string)part [" + partSessionKey
                                    + "]  with value [" + partValue + "]");
                    }
                }
            }
        }
    }
    MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()));
    mimeMessage.setContent(mimeMultipart);
    mimeMessage.saveChanges();
    InputStreamRequestEntity request = new InputStreamRequestEntity(mimeMessage.getInputStream());
    hmethod.setRequestEntity(request);
    String contentTypeMtom = "multipart/related; type=\"application/xop+xml\"; start=\"" + start
            + "\"; start-info=\"text/xml\"; boundary=\"" + mimeMultipart.getBoundary() + "\"";
    Header header = new Header("Content-Type", contentTypeMtom);
    hmethod.addRequestHeader(header);
}

From source file:org.apache.axis.transport.mail.MailSender.java

/**
 * Read from server using POP3//  www.  j av  a2 s .co m
 * @param msgContext
 * @throws Exception
 */
private void readUsingPOP3(String id, MessageContext msgContext) throws Exception {
    // Read the response back from the server
    String pop3Host = msgContext.getStrProp(MailConstants.POP3_HOST);
    String pop3User = msgContext.getStrProp(MailConstants.POP3_USERID);
    String pop3passwd = msgContext.getStrProp(MailConstants.POP3_PASSWORD);

    Reader reader;
    POP3MessageInfo[] messages = null;

    MimeMessage mimeMsg = null;
    POP3Client pop3 = new POP3Client();
    // We want to timeout if a response takes longer than 60 seconds
    pop3.setDefaultTimeout(60000);

    for (int i = 0; i < 12; i++) {
        pop3.connect(pop3Host);

        if (!pop3.login(pop3User, pop3passwd)) {
            pop3.disconnect();
            AxisFault fault = new AxisFault("POP3", "( Could not login to server.  Check password. )", null,
                    null);
            throw fault;
        }

        messages = pop3.listMessages();
        if (messages != null && messages.length > 0) {
            StringBuffer buffer = null;
            for (int j = 0; j < messages.length; j++) {
                reader = pop3.retrieveMessage(messages[j].number);
                if (reader == null) {
                    AxisFault fault = new AxisFault("POP3", "( Could not retrieve message header. )", null,
                            null);
                    throw fault;
                }

                buffer = new StringBuffer();
                BufferedReader bufferedReader = new BufferedReader(reader);
                int ch;
                while ((ch = bufferedReader.read()) != -1) {
                    buffer.append((char) ch);
                }
                bufferedReader.close();
                if (buffer.toString().indexOf(id) != -1) {
                    ByteArrayInputStream bais = new ByteArrayInputStream(buffer.toString().getBytes());
                    Properties prop = new Properties();
                    Session session = Session.getDefaultInstance(prop, null);

                    mimeMsg = new MimeMessage(session, bais);
                    pop3.deleteMessage(messages[j].number);
                    break;
                }
                buffer = null;
            }
        }
        pop3.logout();
        pop3.disconnect();
        if (mimeMsg == null) {
            Thread.sleep(5000);
        } else {
            break;
        }
    }

    if (mimeMsg == null) {
        pop3.logout();
        pop3.disconnect();
        AxisFault fault = new AxisFault("POP3", "( Could not retrieve message list. )", null, null);
        throw fault;
    }

    String contentType = mimeMsg.getContentType();
    String contentLocation = mimeMsg.getContentID();
    Message outMsg = new Message(mimeMsg.getInputStream(), false, contentType, contentLocation);

    outMsg.setMessageType(Message.RESPONSE);
    msgContext.setResponseMessage(outMsg);
    if (log.isDebugEnabled()) {
        log.debug("\n" + Messages.getMessage("xmlRecd00"));
        log.debug("-----------------------------------------------");
        log.debug(outMsg.getSOAPPartAsString());
    }
}

From source file:org.apache.james.core.builder.MimeMessageBuilder.java

public MimeMessageBuilder setMultipartWithSubMessage(MimeMessage mimeMessage)
        throws MessagingException, IOException {
    return setMultipartWithBodyParts(new MimeBodyPart(
            new InternetHeaders(new ByteArrayInputStream(
                    "Content-Type: multipart/mixed".getBytes(StandardCharsets.US_ASCII))),
            IOUtils.toByteArray(mimeMessage.getInputStream())));
}

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

/**
 * Write message body of given mimeessage to the given outputStream
 * /*from ww  w .  jav a 2  s  . c o  m*/
 * @param message
 *            the MimeMessage used as input
 * @param bodyOs
 *            the OutputStream to write the message body to
 * @throws IOException
 * @throws UnsupportedDataTypeException
 * @throws MessagingException
 */
public static void writeMessageBodyTo(MimeMessage message, OutputStream bodyOs)
        throws IOException, MessagingException {
    OutputStream bos;
    InputStream bis;

    try {
        // Get the message as a stream. This will encode
        // objects as necessary, and we have some input from
        // decoding an re-encoding the stream. I'd prefer the
        // raw stream, but see
        bos = MimeUtility.encode(bodyOs, message.getEncoding());
        bis = message.getInputStream();
    } catch (UnsupportedDataTypeException udte) {
        /*
         * If we get an UnsupportedDataTypeException try using the raw input
         * stream as a "best attempt" at rendering a message.
         * 
         * WARNING: JavaMail v1.3 getRawInputStream() returns INVALID
         * (unchanged) content for a changed message. getInputStream() works
         * properly, but in this case has failed due to a missing
         * DataHandler.
         * 
         * MimeMessage.getRawInputStream() may throw a "no content"
         * MessagingException. In JavaMail v1.3, when you initially create a
         * message using MimeMessage APIs, there is no raw content
         * available. getInputStream() works, but getRawInputStream() throws
         * an exception. If we catch that exception, throw the UDTE. It
         * should mean that someone has locally constructed a message part
         * for which JavaMail doesn't have a DataHandler.
         */

        try {
            bis = message.getRawInputStream();
            bos = bodyOs;
        } catch (javax.mail.MessagingException _) {
            throw udte;
        }
    } catch (javax.mail.MessagingException me) {
        /*
         * This could be another kind of MessagingException thrown by
         * MimeMessage.getInputStream(), such as a
         * javax.mail.internet.ParseException.
         * 
         * The ParseException is precisely one of the reasons why the
         * getRawInputStream() method exists, so that we can continue to
         * stream the content, even if we cannot handle it. Again, if we get
         * an exception, we throw the one that caused us to call
         * getRawInputStream().
         */
        try {
            bis = message.getRawInputStream();
            bos = bodyOs;
        } catch (javax.mail.MessagingException _) {
            throw me;
        }
    }

    try {
        IOUtils.copy(bis, bos);
    } finally {
        IOUtils.closeQuietly(bis);
    }
}

From source file:org.apache.james.server.core.MimeMessageUtil.java

/**
 * Write message body of given mimeessage to the given outputStream
 * /*ww w.ja v  a 2 s.com*/
 * @param message
 *            the MimeMessage used as input
 * @param bodyOs
 *            the OutputStream to write the message body to
 * @throws IOException
 * @throws UnsupportedDataTypeException
 * @throws MessagingException
 */
public static void writeMessageBodyTo(MimeMessage message, OutputStream bodyOs)
        throws IOException, MessagingException {
    OutputStream bos;
    InputStream bis;

    try {
        // Get the message as a stream. This will encode
        // objects as necessary, and we have some input from
        // decoding an re-encoding the stream. I'd prefer the
        // raw stream, but see
        bos = MimeUtility.encode(bodyOs, message.getEncoding());
        bis = message.getInputStream();
    } catch (UnsupportedDataTypeException | MessagingException udte) {
        /*
         * If we get an UnsupportedDataTypeException try using the raw input
         * stream as a "best attempt" at rendering a message.
         * 
         * WARNING: JavaMail v1.3 getRawInputStream() returns INVALID
         * (unchanged) content for a changed message. getInputStream() works
         * properly, but in this case has failed due to a missing
         * DataHandler.
         * 
         * MimeMessage.getRawInputStream() may throw a "no content"
         * MessagingException. In JavaMail v1.3, when you initially create a
         * message using MimeMessage APIs, there is no raw content
         * available. getInputStream() works, but getRawInputStream() throws
         * an exception. If we catch that exception, throw the UDTE. It
         * should mean that someone has locally constructed a message part
         * for which JavaMail doesn't have a DataHandler.
         */

        try {
            bis = message.getRawInputStream();
            bos = bodyOs;
        } catch (javax.mail.MessagingException ignored) {
            throw udte;
        }
    }

    try (InputStream input = bis) {
        IOUtils.copy(input, bos);
    }
}

From source file:org.apache.mailet.base.test.MimeMessageBuilder.java

public MimeMessageBuilder setMultipartWithSubMessage(MimeMessage mimeMessage)
        throws MessagingException, IOException {
    return setMultipartWithBodyParts(new MimeBodyPart(
            new InternetHeaders(
                    new ByteArrayInputStream("Content-Type: multipart/mixed".getBytes(Charsets.US_ASCII))),
            IOUtils.toByteArray(mimeMessage.getInputStream())));
}