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:org.nuxeo.ecm.platform.mail.action.TransformMessageAction.java

private void addPartsAsAttachements(List<Part> someMessageParts) throws MessagingException, IOException {
    for (Part part : someMessageParts) {
        setFile(getFileName(part), part.getInputStream());
    }//from www  .  ja  v a2 s .com
}

From source file:com.glaf.mail.MxMailHelper.java

public void processPart(Part p, Mail mail) throws Exception {
    String contentType = p.getContentType();
    InputStream inputStream = null;
    try {/*from   www .  ja  v a2  s.  c  o  m*/
        inputStream = new BufferedInputStream(p.getInputStream());
        if (contentType.startsWith("text/html")) {
            byte[] content = FileUtils.getBytes(inputStream);
            if (content != null && content.length > 0) {
                String html = new String(content);
                mail.setContent(html);
                mail.setMailType(TEXT_HTML);
            }
        } else if (contentType.startsWith("text/plain")) {
            byte[] content = FileUtils.getBytes(inputStream);
            if (content != null && content.length > 0) {
                mail.setContent(new String(content));
                mail.setMailType(TEXT_PLAIN);
            }
        } else if (contentType.startsWith("multipart") || contentType.startsWith("application/octet-stream")) {
            Multipart mp = (Multipart) p.getContent();
            processMultipart(mp, mail);
        }
    } catch (Exception ex) {
        throw ex;
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ex) {
        }
    }

}

From source file:mitm.common.dlp.impl.MimeMessageTextExtractorImpl.java

private void handlePart(Part part, PartContext partContext) throws IOException, MessagingException {
    RewindableInputStream input = new RewindableInputStream(part.getInputStream(), getThreshold());

    try {/*from  ww w . j a v a2  s .c o  m*/
        extractText(input, getPartName(part), partContext);
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:org.apache.hupa.server.servlet.DownloadAttachmentServlet.java

/**
 * Handle to write back the requested attachment
 *//*from   w w w . j  av  a  2s  . c o  m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = (User) request.getSession().getAttribute(SConsts.USER_SESS_ATTR);
    if (user == null)
        throw new ServletException("Invalid session");

    String message_uuid = request.getParameter(SConsts.PARAM_UID);
    String attachmentName = request.getParameter(SConsts.PARAM_NAME);
    String folderName = request.getParameter(SConsts.PARAM_FOLDER);
    String mode = request.getParameter(SConsts.PARAM_MODE);
    boolean inline = "inline".equals(mode);
    if (!inline) {
        response.setHeader("Content-disposition", "attachment; filename=" + attachmentName + "");
    }
    InputStream in = null;
    OutputStream out = response.getOutputStream();

    IMAPFolder folder = null;
    try {
        Store store = cache.get(user);
        folder = (IMAPFolder) store.getFolder(folderName);
        if (folder.isOpen() == false) {
            folder.open(Folder.READ_ONLY);
        }
        Message m = folder.getMessageByUID(Long.parseLong(message_uuid));

        Object content = m.getContent();
        Part part = MessageUtils.handleMultiPart(logger, content, attachmentName);
        if (part.getContentType() != null) {
            response.setContentType(part.getContentType());
        } else {
            response.setContentType("application/download");
        }

        handleAttachmentData(request, m, attachmentName, part.getInputStream(), out);
        return;
    } catch (Exception e) {
        logger.error("Error while downloading attachment " + attachmentName + " of message " + message_uuid
                + " for user " + user.getName(), e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        if (folder != null) {
            try {
                folder.close(false);
            } catch (MessagingException e) {
            }
        }
    }
}

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Attach.java

private void saveFile(Part part, StringBuffer buffer) {
    BufferedOutputStream outS = null;
    InputStream is = null;/*from   w  w  w  . j av a 2  s .com*/
    byte[] buff = new byte[2048];
    try {
        outS = new BufferedOutputStream(new FileOutputStream(buffer.toString()));
        is = part.getInputStream();
        int ret = 0, count = 0;
        while ((ret = is.read(buff)) > 0) {
            outS.write(buff, 0, ret);
            count += ret;
        }
        setSize(new Long(count));
    } catch (Exception e) {
        log.error(
                "Could not store attach in the filesystem. Verify the configuration of your filesystem properties. Attach: "
                        + getFileName() + " - " + e.getClass().getName() + " - " + e.getMessage());
        throw new RuntimeException("Could not store attach in filesystem. Attach " + getFileName());
    } finally {
        if (outS != null)
            try {
                outS.close();
            } catch (IOException e) {
            }
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
            }
    }
}

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

private void processSingleMessagePart(Part part) throws MessagingException, IOException {
    String partContentType = part.getContentType();
    String partFileName = getFileName(part);

    if (partFileName != null) {
        log.debug("Add named attachment: " + partFileName);
        setFile(partFileName, part.getInputStream());
        return;/*from  w w w. j  a  v  a2  s .  c o  m*/
    }

    if (!contentTypeIsReadableText(partContentType)) {
        log.debug("Add unnamed binary attachment.");
        setFile(null, part.getInputStream());
        return;
    }

    if (contentTypeIsPlainText(partContentType)) {
        log.debug("found plain text unnamed attachment [save for later processing]");
        messageBodyParts.get("text").add(part);
        return;
    }

    log.debug("found html unnamed attachment [save for later processing]");
    messageBodyParts.get("html").add(part);
}

From source file:com.cubusmail.server.services.RetrieveImageServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from   w  ww .  j  a  v  a2  s  .  com
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean isThumbnail = Boolean.valueOf(request.getParameter("thumbnail")).booleanValue();

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            if (isThumbnail) {
                List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
                int index = Integer.valueOf(attachmentIndex);

                MimePart retrievePart = attachmentList.get(index);

                ContentType contentType = new ContentType(retrievePart.getContentType());
                response.setContentType(contentType.getBaseType());

                BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
                OutputStream outputStream = response.getOutputStream();

                writeScaledImage(bufInputStream, outputStream);

                bufInputStream.close();
                outputStream.flush();
                outputStream.close();
            } else {
                Part imagePart = findImagePart(msg);
                if (imagePart != null) {
                    ContentType contentType = new ContentType(imagePart.getContentType());
                    response.setContentType(contentType.getBaseType());

                    BufferedInputStream bufInputStream = new BufferedInputStream(imagePart.getInputStream());
                    OutputStream outputStream = response.getOutputStream();

                    byte[] inBuf = new byte[1024];
                    int len = 0;
                    int total = 0;
                    while ((len = bufInputStream.read(inBuf)) > 0) {
                        outputStream.write(inBuf, 0, len);
                        total += len;
                    }

                    bufInputStream.close();
                    outputStream.flush();
                    outputStream.close();
                }
            }
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

private String getCheckSum(Part part) throws IOException, MessagingException {
    Attach attach = new Attach();
    attach.buildMd5Checksum(part.getInputStream());
    return attach.getMd5Checksum();
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

/**
 * Saves an attachment as a file, and stores the path in the message.
 *
 * @param part the part corresponding to the attachment.
 * @param componentId the id of the mailing list component.
 * @param messageId the id of the message (email id).
 * @return the absolute path to the file.
 * @throws IOException/*from  w  w w . j a  va 2s .c  om*/
 * @throws MessagingException
 */
public String saveAttachment(Part part, String componentId, String messageId)
        throws IOException, MessagingException {
    File parentDir = new File(
            FileRepositoryManager.getAbsolutePath(componentId) + replaceSpecialChars(messageId));
    if (!parentDir.exists()) {
        parentDir.mkdirs();
    }
    File targetFile = new File(parentDir, getFileName(part));
    InputStream partIn = part.getInputStream();
    try {

        FileUtil.writeFile(targetFile, partIn);

    } finally {
        IOUtils.closeQuietly(partIn);
    }
    return targetFile.getAbsolutePath();
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

private void addEmailAttachmentsToJob(final DepositEmailConfiguration depositEmailConfiguration,
        final MimeMessage mimeMessage, final MultiFilesJob job)
        throws MessagingException, IOException, FileNotFoundException {

    final String jobConfigurationFileName = depositEmailConfiguration.getJobConfigurationFileName();
    if (StringUtils.isNotBlank(jobConfigurationFileName)) {
        final File jobConfigurationFile = getJobConfigurationFile(
                depositEmailConfiguration.getApplicationName(), jobConfigurationFileName);
        job.addFile(Constants.MULTIPLE_FILES_JOB_CONFIGURATION, new FileInputStream(jobConfigurationFile));
    }/*from www.jav  a 2s .com*/

    final Object content = mimeMessage.getContent();
    Validate.isTrue(content instanceof Multipart, "only multipart emails can be processed");

    final Multipart multipart = (Multipart) content;
    for (int i = 0, n = multipart.getCount(); i < n; i++) {
        final Part part = multipart.getBodyPart(i);

        final String disposition = part.getDisposition();

        if ((disposition != null)
                && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
            final String name = part.getFileName();
            final String contentType = StringUtils.substringBefore(part.getContentType(), ";");
            MultiFilesJob.addDataToJob(contentType, name, part.getInputStream(), job);
        }
    }
}