Example usage for javax.mail Part getInputStream

List of usage examples for javax.mail Part getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException, MessagingException;

Source Link

Document

Return an input stream for this part's "content".

Usage

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

/**
 * Extracts the message from the RFC822 attachment.
 * @throws MessagingException /*  w  w  w  .j a  v a 2  s  .  c  om*/
 * @throws IOException 
 */
public static MimeMessage extractFromRFC822(Part rfc822) throws IOException, MessagingException {
    if (!rfc822.isMimeType("message/rfc822")) {
        throw new MessagingException("Part is-not-a message/rfc822 but " + rfc822.getContentType());
    }

    return new MimeMessage(MailSession.getDefaultSession(), rfc822.getInputStream());
}

From source file:mailbox.CreationViaEmail.java

private static Attachment saveAttachment(Part partToAttach, Resource container)
        throws MessagingException, IOException, NoSuchAlgorithmException {
    Attachment attach = new Attachment();
    String fileName = MimeUtility.decodeText(partToAttach.getFileName());
    attach.store(partToAttach.getInputStream(), fileName, container);
    if (!attach.mimeType.equalsIgnoreCase(partToAttach.getContentType())) {
        Logger.info("The email says the content type is '" + partToAttach.getContentType()
                + "' but Yobi determines it is '" + attach.mimeType + "'");
    }/*from  ww  w.  j av  a2  s .  com*/

    return attach;
}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private static byte[] readInputStream(Part _part) throws IOException, MessagingException {
    InputStream ins = null;/*from  ww w .  j  a va  2s.com*/
    ByteArrayOutputStream bos = null;
    try {
        ins = _part.getInputStream();
        bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int read;
        while ((read = ins.read(buffer)) != -1) {
            bos.write(buffer, 0, read);
        }
        return bos.toByteArray();
    } finally {
        if (ins != null)
            try {
                ins.close();
            } catch (IOException ignored) {
            }
        if (bos != null)
            try {
                bos.close();
            } catch (IOException ignored) {
            }
    }
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

private static EmailAttachment createEmailAttachment(Part part, String fileName)
        throws java.io.IOException, javax.mail.MessagingException {
    EmailAttachment emailAttachment = new EmailAttachment();
    File file = MailReader.saveFile(fileName, part.getInputStream());
    emailAttachment.setFile(file);/*from   ww  w. ja v  a 2s.co  m*/
    emailAttachment.setFileName(fileName);
    String cid = null;
    String[] contentIDs = part.getHeader("Content-ID");
    if (contentIDs != null && contentIDs.length > 0) {
        cid = contentIDs[0];
        if (cid != null && cid.startsWith("<")) {
            cid = cid.substring(1, cid.length() - 1);
        }
    }
    emailAttachment.setCid(cid);
    return emailAttachment;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

private static String salvaImagenEnFichero(Part unaParte)
        throws FileNotFoundException, MessagingException, IOException {
    FileOutputStream fichero = new FileOutputStream(
            "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\archivosMail\\verCorreo\\"
                    + unaParte.getFileName());
    InputStream imagen = unaParte.getInputStream();
    byte[] bytes = new byte[1000];
    int leidos = 0;

    while ((leidos = imagen.read(bytes)) > 0) {
        fichero.write(bytes, 0, leidos);
    }/*w ww.  ja v  a  2  s. co m*/
    return unaParte.getFileName();
}

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.RFC822ToTextConverter.java

protected static byte[] extractTextFromMessagePart(Part p) throws Exception {
    ContentType contentType = new ContentType(p.getContentType());
    String baseType = contentType.getBaseType();
    if (TXT_MT.equals(baseType)) {
        Object content = p.getContent();
        if (content instanceof String) {
            return ((String) content).getBytes();
        } else {//from w  w w. ja  v a2 s . c  o  m
            return null;
        }
    }
    ConversionService cs = Framework.getLocalService(ConversionService.class);

    String converterName = cs.getConverterName(baseType, TXT_MT);
    if (converterName == null) {
        return null;
    } else {
        BlobHolder result = cs.convert(converterName, new SimpleBlobHolder(new FileBlob(p.getInputStream())),
                null);
        return result.getBlob().getByteArray();
    }
}

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 .  j ava2s.c  o m*/
 * 
 * @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:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java

public static void handlePart(String foldername, Part part) throws MessagingException, IOException {
    String disposition = part.getDisposition();
    // String contentType = part.getContentType();

    if ((disposition != null)
            && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE))) {
        saveFile(foldername, MimeUtility.decodeText(part.getFileName()), part.getInputStream());
    }/*from  w ww. ja  v  a  2s. co  m*/
}

From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java

/**
 * Interprets the body accordingly to the charset used. It relies on the content type being
 * ****;charset={charset};******// www  .  java 2 s  .c om
 *
 * @return the decoded String
 */
protected static String decodeMailBody(Part part) throws MessagingException, IOException {

    String encoding = null;

    // try to get encoding from header rather than from Stream !
    // unfortunately, this does not seem to be reliable ...
    /*
     * String[] cteHeader = part.getHeader("Content-Transfer-Encoding"); if (cteHeader!=null && cteHeader.length>0)
     * { encoding = cteHeader[0].toLowerCase(); }
     */

    // fall back to default sniffing
    // that will actually read the stream from server
    if (encoding == null) {
        encoding = MimeUtility.getEncoding(part.getDataHandler());
    }

    InputStream is = null;
    try {
        is = MimeUtility.decode(part.getInputStream(), encoding);
    } catch (IOException ex) {
        log.error("Unable to read content", ex);
        return "";
    }

    String contType = part.getContentType();
    final String charsetIdentifier = "charset=";
    final String ISO88591 = "iso-8859-1";
    final String WINDOWS1252 = "windows-1252";
    int offset = contType.indexOf(charsetIdentifier);
    String charset = "";
    if (offset >= 0) {
        charset = contType.substring(offset + charsetIdentifier.length());
        offset = charset.indexOf(";");
        if (offset > 0) {
            charset = charset.substring(0, offset);
        }
    }
    // Charset could be like "utf-8" or utf-8
    if (!"".equals(charset)) {
        charset = charset.replaceAll("\"", "");
    }
    log.debug("Content type: " + contType + "; charset: " + charset);
    if (charset.equalsIgnoreCase(ISO88591)) {
        // see
        // http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#character1
        // for more details see http://en.wikipedia.org/wiki/ISO_8859-1
        // section "ISO-8859-1 and Windows-1252 confusion"
        charset = WINDOWS1252;
        log.debug("Using replacing charset: " + charset);
    }
    String ret;
    byte[] streamContent = FileUtils.readBytes(is);
    if ("".equals(charset)) {
        ret = new String(streamContent);
    } else {
        try {
            ret = new String(streamContent, charset);
        } catch (UnsupportedEncodingException e) {
            // try without encoding
            ret = new String(streamContent);
        }
    }
    return ret;
}

From source file:org.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java

@SuppressWarnings("unchecked")
protected static void getAttachmentParts(Part p, String defaultFilename, MimetypeRegistry mimeService,
        ExecutionContext context) throws MessagingException, IOException {
    String filename = getFilename(p, defaultFilename);
    List<Blob> blobs = (List<Blob>) context.get(ATTACHMENTS_KEY);

    if (!p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // no disposition => consider it may be body
        if (disp == null && !context.containsKey(BODY_KEY)) {
            // this will need to be parsed
            context.put(BODY_KEY, p.getContent());
        } else if (disp != null
                && (disp.equalsIgnoreCase(Part.ATTACHMENT) || (disp.equalsIgnoreCase(Part.INLINE)
                        && !(p.isMimeType("text/*") || p.isMimeType("image/*"))))) {
            log.debug("Saving attachment to file " + filename);
            Blob blob = Blobs.createBlob(p.getInputStream());
            String mime = DEFAULT_BINARY_MIMETYPE;
            try {
                if (mimeService != null) {
                    ContentType contentType = new ContentType(p.getContentType());
                    mime = mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob,
                            contentType.getBaseType());
                }/*  w w w.ja v  a 2  s.c  o  m*/
            } catch (MimetypeDetectionException e) {
                log.error(e);
            }
            blob.setMimeType(mime);

            blob.setFilename(filename);

            blobs.add(blob);

            // for debug
            // File f = new File(filename);
            // ((MimeBodyPart) p).saveFile(f);

            log.debug("---------------------------");

        } else {
            log.debug(String.format("Ignoring part with type %s", p.getContentType()));
        }
    }

    if (p.isMimeType("multipart/*")) {
        log.debug("This is a Multipart");
        log.debug("---------------------------");
        Multipart mp = (Multipart) p.getContent();

        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            getAttachmentParts(mp.getBodyPart(i), defaultFilename, mimeService, context);
        }
    } else if (p.isMimeType(MESSAGE_RFC822_MIMETYPE)) {
        log.debug("This is a Nested Message");
        log.debug("---------------------------");
        getAttachmentParts((Part) p.getContent(), defaultFilename, mimeService, context);
    }

}