Example usage for javax.mail.internet MimeMessage getRawInputStream

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

Introduction

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

Prototype

public InputStream getRawInputStream() throws MessagingException 

Source Link

Document

Return an InputStream to the raw data with any Content-Transfer-Encoding intact.

Usage

From source file:com.cubusmail.mail.text.MessageTextUtil.java

/**
 * Reads the string out of part's input stream. On first try the input
 * stream retrieved by <code>javax.mail.Part.getInputStream()</code> is
 * used. If an I/O error occurs (<code>java.io.IOException</code>) then the
 * next try is with part's raw input stream. If everything fails an empty
 * string is returned./*from  w  w  w  . jav  a2s .com*/
 * 
 * @param p
 *            - the <code>javax.mail.Part</code> object
 * @param ct
 *            - the part's content type
 * @return the string read from part's input stream or the empty string ""
 *         if everything failed
 * @throws MessagingException
 *             - if an error occurs in part's getter methods
 */
public static String readPart(final Part p) throws MessagingException {

    String contentType = p.getContentType();
    ContentType type = new ContentType(contentType);

    /*
     * Use specified charset if available else use default one
     */
    String charset = type.getParameter("charset");
    if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
        charset = CubusConstants.DEFAULT_CHARSET;
    }
    try {
        return readStream(p.getInputStream(), charset);
    } catch (final IOException e) {
        /*
         * Try to get data from raw input stream
         */
        final InputStream inStream;
        if (p instanceof MimeBodyPart) {
            final MimeBodyPart mpb = (MimeBodyPart) p;
            inStream = mpb.getRawInputStream();
        } else if (p instanceof MimeMessage) {
            final MimeMessage mm = (MimeMessage) p;
            inStream = mm.getRawInputStream();
        } else {
            inStream = null;
        }
        if (inStream == null) {
            /*
             * Neither a MimeBodyPart nor a MimeMessage
             */
            return "";
        }
        try {
            return readStream(inStream, charset);
        } catch (final IOException e1) {
            log.error(e1.getLocalizedMessage(), e1);
            return e1.getLocalizedMessage();
            // return STR_EMPTY;
        } finally {
            try {
                inStream.close();
            } catch (final IOException e1) {
                log.error(e1.getLocalizedMessage(), e1);
            }
        }
    }
}

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

public static MimeBodyPart makeContentBodyPartRaw(MimeMessage sourceMessage, HeaderMatcher matcher)
        throws IOException, MessagingException {
    /*/*from  w w w .ja  v  a  2  s .co  m*/
     * getRawInputStream() can throw a MessagingException when the source message is a MimeMessage
     * that is created in code (ie. not from a stream)
     */
    InputStream messageStream = sourceMessage.getRawInputStream();

    MimeBodyPart newBodyPart = new MimeBodyPart(messageStream);

    HeaderUtils.copyHeaders(sourceMessage, newBodyPart, matcher);

    return newBodyPart;
}

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

/**
 * This is the only way I know of to create a new MimeBodyPart from another Message which is safe
 * for signed email. All other methods break the signature when quoted printable soft breaks are used.
 * //  w  w w  .ja va  2  s  .com
 * example of quoted printable soft breaks:
 * 
 * Content-Transfer-Encoding: quoted-printable
        
 * soft break example =
 * another line =
 *
 * All other methods will re-encode and removes the soft breaks.
 * 
 * @param sourceMessage
 * @param matcher
 * @return
 * @throws IOException
 * @throws MessagingException
 */
@SuppressWarnings("unchecked")
public static MimeBodyPart makeContentBodyPartRawBytes(MimeMessage sourceMessage, HeaderMatcher matcher)
        throws IOException, MessagingException {
    /*
     * getRawInputStream() can throw a MessagingException when the source message is a MimeMessage
     * that is created in code (ie. not from a stream)
     */
    InputStream messageStream = sourceMessage.getRawInputStream();

    byte[] rawMessage = IOUtils.toByteArray(messageStream);

    InternetHeaders destinationHeaders = new InternetHeaders();

    Enumeration<Header> sourceHeaders = sourceMessage.getAllHeaders();

    HeaderUtils.copyHeaders(sourceHeaders, destinationHeaders, matcher);

    MimeBodyPart newBodyPart = new MimeBodyPart(destinationHeaders, rawMessage);

    return newBodyPart;
}

From source file:org.apache.james.transport.mailets.LogMessage.java

private void logBody(MimeMessage message) throws MessagingException, IOException {
    if (body) {/*from   w w w.  j a  v  a  2  s. c o  m*/
        InputStream inputStream = ByteStreams.limit(message.getRawInputStream(), lengthToLog(message));
        log(IOUtils.toString(inputStream));
    }
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * @param part/*  w  w  w .jav  a 2s.co m*/
 * @return
 * @throws MessagingException
 */
private String readPart(Part part) throws MessagingException {

    try {
        return readStream(part.getInputStream());

    } catch (IOException e) {

        /* 
         * Try to get message from raw input stream
         */
        final InputStream stream;

        if (part instanceof MimeBodyPart) {

            final MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
            stream = mimeBodyPart.getRawInputStream();

        } else if (part instanceof MimeMessage) {

            final MimeMessage mm = (MimeMessage) part;
            stream = mm.getRawInputStream();

        } else {
            stream = null;
        }

        if (stream == null) {
            /* 
             * Neither a MimeBodyPart nor a MimeMessage
             */
            return "";
        }

        try {
            return readStream(stream);

        } catch (IOException e1) {
            return "";

        } finally {
            try {
                stream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    }
}

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

/**
 * Write message body of given mimeessage to the given outputStream
 * //from  www  . ja v a 2s .  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 | 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.james.core.MimeMessageUtil.java

/**
 * Write message body of given mimeessage to the given outputStream
 * //from   w w  w . j  av  a 2  s  . c  om
 * @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:com.zotoh.maedr.device.PopIO.java

private void getMsgs() throws Exception {

    int cnt = _fd.getMessageCount();

    tlog().debug("PopIO: count of new messages: {}", cnt);
    if (cnt <= 0)
        return;//w w  w . ja v  a2 s .  c o m

    StringBuilder hds = new StringBuilder(512);
    Message[] msgs = _fd.getMessages();
    MimeMessage mm;
    StreamData data;
    String s;

    for (int i = 0; i < msgs.length; ++i) {
        mm = (MimeMessage) msgs[i];
        //TODO
        //_fd.getUID(mm);
        // read all the header lines
        hds.setLength(0);
        for (Enumeration<?> en = mm.getAllHeaderLines(); en.hasMoreElements();) {
            s = (String) en.nextElement();
            //                if (s.toLowerCase().indexOf(CTL) >= 0) {}
            //                else
            hds.append(s).append("\r\n");
        }

        data = StreamUte.readStream(mm.getRawInputStream());
        try {
            dispatch(new POP3Event(this, hds.toString(), data));
        } finally {
            if (_delete) {
                mm.setFlag(Flags.Flag.DELETED, true);
            }
        }
    }
}

From source file:com.stimulus.archiva.store.MessageStore.java

public void writeCorruptedEmail(MimeMessage message, File file) throws MessageStoreException {
    logger.debug("writeCorruptedEmail");
    InputStream is = null;// w  ww.  ja va 2s  . co m
    OutputStream os = null;
    try {
        logger.debug("writing corrupted email to quarantine {filename='" + file + "'}");
        os = new BufferedOutputStream(new FileOutputStream(file));
        is = message.getRawInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        int c = 0;
        while ((c = bis.read()) != -1) {
            os.write(c);
        }
    } catch (Throwable ex) {
        StreamUtil.emptyStream(is);
        throw new MessageStoreException("failed to write corrupted email to quarantine:" + ex.getMessage(), ex,
                logger);
    } finally {
        try {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.apache.james.pop3server.POP3Handler.java

/**
 * Writes the content of the message, up to a total number of lines, out to 
 * an OutputStream./*from  w w w . jav  a  2  s.  c om*/
 *
 * @param out the OutputStream to which to write the content
 * @param lines the number of lines to write to the stream
 *
 * @throws MessagingException if the MimeMessage is not set for this MailImpl
 * @throws IOException if an error occurs while reading or writing from the stream
 */
public void writeMessageContentTo(MimeMessage message, OutputStream out, int lines)
        throws IOException, MessagingException {
    String line;
    BufferedReader br;
    if (message != null) {
        br = new BufferedReader(new InputStreamReader(message.getRawInputStream()));
        try {
            while (lines-- > 0) {
                if ((line = br.readLine()) == null) {
                    break;
                }
                line += "\r\n";
                out.write(line.getBytes());
            }
        } finally {
            br.close();
        }
    } else {
        throw new MessagingException("No message set for this MailImpl.");
    }
}