Example usage for javax.mail.internet MimeBodyPart getInputStream

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

Introduction

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

Prototype

@Override
public InputStream getInputStream() throws IOException, MessagingException 

Source Link

Document

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

Usage

From source file:com.hmsinc.epicenter.surveillance.notification.MailingEventNotifierTest.java

private InputStream getMessageAsStream() throws IOException, MessagingException {
    MimeMessage message = (MimeMessage) sentMessages.get(0);
    MimeMultipart mm = (MimeMultipart) message.getContent();
    MimeBodyPart body0 = (MimeBodyPart) mm.getBodyPart(0);
    return body0.getInputStream();
}

From source file:com.hmsinc.epicenter.surveillance.notification.MailingEventNotifierTest.java

@Test
public void shouldHaveCorrectStructure() throws MessagingException, IOException {
    MimeMessage message = (MimeMessage) sentMessages.get(0);

    MimeMultipart mm = (MimeMultipart) message.getContent();
    assertEquals(1, mm.getCount());//from  w w w. j a v  a  2s. c  o m

    MimeBodyPart body0 = (MimeBodyPart) mm.getBodyPart(0);
    assertNotNull(loadContent(body0.getInputStream()));
}

From source file:com.adaptris.core.mail.attachment.MimeMailCreator.java

/**
 * @see MailContentCreator#createAttachments(com.adaptris.core.AdaptrisMessage)
 *//* w  w w  . ja  v a2s  .c o  m*/
@Override
public List<MailAttachment> createAttachments(AdaptrisMessage msg) throws MailException {
    if (bodySelector == null) {
        throw new MailException("No way of selecting the body");
    }
    List<MailAttachment> attachments = new ArrayList<MailAttachment>();
    try {
        BodyPartIterator mp = MimeHelper.createBodyPartIterator(msg);
        MimeBodyPart body = bodySelector.select(mp);
        for (int i = 0; i < mp.size(); i++) {
            MimeBodyPart attachment = mp.getBodyPart(i);
            if (!attachment.equals(body)) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                StreamUtil.copyStream(attachment.getInputStream(), out);
                out.flush();
                attachments.add(new MailAttachment(out.toByteArray(), getAttachmentFileName(attachment),
                        getContentType(attachment))
                                .withContentTransferEncoding(getContentTransferEncoding(attachment)));
            }
        }
    } catch (Exception e) {
        throw new MailException(e);
    }
    return attachments;
}

From source file:com.adaptris.core.MimeEncoderImpl.java

protected void addPartsToMessage(BodyPartIterator input, AdaptrisMessage msg)
        throws IOException, MessagingException {
    MimeBodyPart payloadPart = Args.notNull(input.getBodyPart(PAYLOAD_CONTENT_ID), "payload");
    MimeBodyPart metadataPart = Args.notNull(input.getBodyPart(METADATA_CONTENT_ID), "metadata");
    try (InputStream payloadIn = payloadPart.getInputStream();
            InputStream metadata = metadataPart.getInputStream();
            OutputStream out = msg.getOutputStream()) {
        IOUtils.copy(payloadIn, out);//from w ww  .ja v  a  2  s .c  o m
        msg.setMetadata(getMetadataSet(metadata));
    }
    if (retainUniqueId()) {
        msg.setUniqueId(input.getMessageID());
    }
}

From source file:com.adaptris.core.mail.attachment.MimeMailCreator.java

/**
 * @see com.adaptris.core.mail.attachment.MailContentCreator#createBody(com.adaptris.core.AdaptrisMessage)
 */// w ww  .  jav a2  s . c om
@Override
public MailContent createBody(AdaptrisMessage msg) throws MailException {
    if (bodySelector == null) {
        throw new MailException("No way of selecting the body");
    }
    MailContent result = null;
    try {
        BodyPartIterator mp = MimeHelper.createBodyPartIterator(msg);
        MimeBodyPart part = bodySelector.select(mp);
        if (part == null) {
            throw new CoreException("No part selected as the body");
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StreamUtil.copyStream(part.getInputStream(), out);
        out.flush();
        result = new MailContent(out.toByteArray(), getContentType(part));
    } catch (Exception e) {
        throw new MailException(e);
    }
    return result;
}

From source file:org.apache.synapse.transport.mail.MailUtils.java

public InputStream getInputStream(Object message) {
    try {/*  ww  w . j  a  va 2s. c  o  m*/
        if (message instanceof MimeMessage) {
            MimeMessage msg = (MimeMessage) message;
            if (msg.getContent() instanceof Multipart) {
                MimeBodyPart firstTextPart = null;

                Multipart mp = (Multipart) msg.getContent();
                for (int i = 0; i < mp.getCount(); i++) {
                    MimeBodyPart mbp = (MimeBodyPart) mp.getBodyPart(i);
                    String contType = mbp.getContentType();

                    if (contType != null && (contType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) != -1
                            || contType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) != -1)) {
                        // this part is a SOAP 11 or 12 payload, treat this as the message
                        return mbp.getInputStream();
                    } else if (mbp == null && contType.indexOf("plain/text") != -1) {
                        firstTextPart = mbp;
                    }
                }
                // if a soap 11 or soap12 payload was not found, treat first text part as message
                return firstTextPart.getInputStream();

            } else {
                return ((Message) message).getInputStream();
            }
        }
    } catch (Exception e) {
        handleException("Error creating an input stream to : " + ((Message) message).getMessageNumber(), e);
    }
    return null;
}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **//* w  ww .ja  va2 s. c o m*/

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}

From source file:com.adaptris.core.services.mime.MimePartSelector.java

/**
 * @see com.adaptris.core.Service#doService(com.adaptris.core.AdaptrisMessage)
 *//*from   w  w  w.  j a  va 2  s  .c  om*/
@Override
public void doService(AdaptrisMessage msg) throws ServiceException {
    try {
        BodyPartIterator mp = MimeHelper.createBodyPartIterator(msg);
        MimeBodyPart part = selector.select(mp);
        if (part != null) {
            if (preserveHeadersAsMetadata()) {
                addHeadersAsMetadata(mp.getHeaders().getAllHeaders(), headerPrefix(), msg);
            }
            if (preservePartHeadersAsMetadata()) {
                addHeadersAsMetadata(part.getAllHeaders(), partHeaderPrefix(), msg);
            }
            StreamUtil.copyAndClose(part.getInputStream(), msg.getOutputStream());
            if (markAsNonMime()) {
                if (msg.containsKey(CoreConstants.MSG_MIME_ENCODED)) {
                    msg.removeMetadata(msg.getMetadata(CoreConstants.MSG_MIME_ENCODED));
                }
            }
        } else {
            log.warn("Could not select a MimePart for extraction, ignoring");
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:org.apache.olingo.fit.V3Services.java

@Override
public InputStream exploreMultipart(final List<Attachment> attachments, final String boundary,
        final boolean contineOnError) throws IOException {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    Response res = null;//from  w ww.  j  a  v  a2  s. c o m
    boolean goon = true;
    for (int i = 0; i < attachments.size() && goon; i++) {
        try {
            final Attachment obj = attachments.get(i);
            bos.write(("--" + boundary).getBytes());
            bos.write(Constants.CRLF);

            final Object content = obj.getDataHandler().getContent();
            if (content instanceof MimeMultipart) {
                final Map<String, String> references = new HashMap<String, String>();

                final String cboundary = "changeset_" + UUID.randomUUID().toString();
                bos.write(("Content-Type: multipart/mixed;boundary=" + cboundary).getBytes());
                bos.write(Constants.CRLF);
                bos.write(Constants.CRLF);

                final ByteArrayOutputStream chbos = new ByteArrayOutputStream();
                String lastContebtID = null;
                try {
                    for (int j = 0; j < ((MimeMultipart) content).getCount(); j++) {
                        final MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) content).getBodyPart(j);
                        lastContebtID = part.getContentID();
                        addChangesetItemIntro(chbos, lastContebtID, cboundary);

                        res = bodyPartRequest(new MimeBodyPart(part.getInputStream()), references);
                        if (res == null || res.getStatus() >= 400) {
                            throw new Exception("Failure processing changeset");
                        }

                        addSingleBatchResponse(res, lastContebtID, chbos);
                        references.put("$" + lastContebtID, res.getHeaderString("Location"));
                    }

                    bos.write(chbos.toByteArray());
                    IOUtils.closeQuietly(chbos);

                    bos.write(("--" + cboundary + "--").getBytes());
                    bos.write(Constants.CRLF);
                } catch (Exception e) {
                    LOG.warn("While processing changeset", e);
                    IOUtils.closeQuietly(chbos);

                    addChangesetItemIntro(bos, lastContebtID, cboundary);

                    if (res == null || res.getStatus() < 400) {
                        addErrorBatchResponse(e, "1", bos);
                    } else {
                        addSingleBatchResponse(res, lastContebtID, bos);
                    }

                    goon = contineOnError;
                }
            } else {
                addItemIntro(bos);

                res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream()));

                if (res.getStatus() >= 400) {
                    goon = contineOnError;
                    throw new Exception("Failure processing changeset");
                }

                addSingleBatchResponse(res, bos);
            }
        } catch (Exception e) {
            if (res == null || res.getStatus() < 400) {
                addErrorBatchResponse(e, bos);
            } else {
                addSingleBatchResponse(res, bos);
            }
        }
    }

    bos.write(("--" + boundary + "--").getBytes());

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:dtw.webmail.util.FormdataMultipart.java

/**
 * Processes a body part of the form-data.
 * Extracts parameters and set values, and
 * leaves over the attachments./*from  w ww  .j a  v  a 2 s .  c  o  m*/
 *
 * @param mbp the <tt>MimeBodyPart</tt> to be processed.
 *
 * @throws IOException if i/o operations fail.
 * @throws MessagingException if parsing or part handling with
 *         Mail API classes fails.
 */
private void processBodyPart(MimeBodyPart mbp) throws MessagingException, IOException {

    //String contenttype=new String(mbp.getContentType());
    //JwmaKernel.getReference().debugLog().write("Processing "+contenttype);

    //check if a content-type is given
    String[] cts = mbp.getHeader("Content-Type");
    if (cts == null || cts.length == 0) {
        //this is a parameter, get it out and
        //remove the part.
        String controlname = extractName((mbp.getHeader("Content-Disposition"))[0]);

        //JwmaKernel.getReference().debugLog().write("Processing control:"+controlname);
        //retrieve value observing encoding
        InputStream in = mbp.getInputStream();
        String[] encoding = mbp.getHeader("Content-Transfer-Encoding");
        if (encoding != null && encoding.length > 0) {
            in = MimeUtility.decode(in, encoding[0]);
        }

        String value = extractValue(in);
        if (value != null || !value.trim().equals("")) {
            addParameter(controlname, value);
        }
        //flag removal
        m_Removed = true;
        removeBodyPart(mbp);
    } else {
        String filename = extractFileName((mbp.getHeader("Content-Disposition"))[0]);

        //normally without file the control should be not successful.
        //but neither netscape nor mircosoft iexploder care much.
        //the only feature is an empty filename.
        if (filename.equals("")) {
            //kick it out too
            m_Removed = true;
            removeBodyPart(mbp);
        } else {

            //JwmaKernel.getReference().debugLog().write("Incoming filename="+filename);

            //IExploder sends files with complete path.
            //jwma doesnt want this.
            int lastindex = filename.lastIndexOf("\\");
            if (lastindex != -1) {
                filename = filename.substring(lastindex + 1, filename.length());
            }

            //JwmaKernel.getReference().debugLog().write("Outgoing filename="+filename);

            //Observe a possible encoding
            InputStream in = mbp.getInputStream();
            String[] encoding = mbp.getHeader("Content-Transfer-Encoding");
            if (encoding != null && encoding.length > 0) {
                in = MimeUtility.decode(in, encoding[0]);
            }
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            OutputStream out = (OutputStream) bout;

            int i = 0;
            while ((i = in.read()) != -1) {
                //maybe more efficient in buffers, but well
                out.write(i);
            }
            out.flush();
            out.close();

            //create the datasource
            MimeBodyPartDataSource mbpds = new MimeBodyPartDataSource(
                    //    contenttype,filename,bout.toByteArray()
                    cts[0], filename, bout.toByteArray());

            //Re-set the Content-Disposition header, in case
            //the file name was changed
            mbp.removeHeader("Content-Disposition");
            mbp.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

            //set a base64 transferencoding und the data handler
            mbp.addHeader("Content-Transfer-Encoding", "base64");
            mbp.setDataHandler(new DataHandler(mbpds));
        }
    }
}