Example usage for javax.mail.internet MimeMultipart MimeMultipart

List of usage examples for javax.mail.internet MimeMultipart MimeMultipart

Introduction

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

Prototype

public MimeMultipart(DataSource ds) throws MessagingException 

Source Link

Document

Constructs a MimeMultipart object and its bodyparts from the given DataSource.

Usage

From source file:org.nuxeo.client.api.marshaller.NuxeoResponseConverterFactory.java

@Override
public T convert(ResponseBody value) throws IOException {
    // Checking custom marshallers with the type of the method clientside.
    if (nuxeoMarshaller != null) {
        String response = value.string();
        logger.debug(response);//from   w w w .j  av  a2 s. c o m
        JsonParser jsonParser = objectMapper.getFactory().createParser(response);
        return nuxeoMarshaller.read(jsonParser);
    }
    // Checking if multipart outputs.
    MediaType mediaType = MediaType.parse(value.contentType().toString());
    if (!(mediaType.type().equals(ConstantsV1.APPLICATION) && mediaType.subtype().equals(ConstantsV1.JSON))
            && !(mediaType.type().equals(ConstantsV1.APPLICATION)
                    && mediaType.subtype().equals(ConstantsV1.JSON_NXENTITY))) {
        if (mediaType.type().equals(ConstantsV1.MULTIPART)) {
            Blobs blobs = new Blobs();
            try {
                MimeMultipart mp = new MimeMultipart(
                        new ByteArrayDataSource(value.byteStream(), mediaType.toString()));
                int size = mp.getCount();
                for (int i = 0; i < size; i++) {
                    BodyPart part = mp.getBodyPart(i);
                    blobs.add(part.getFileName(), IOUtils.copyToTempFile(part.getInputStream()));
                }
            } catch (MessagingException reason) {
                throw new IOException(reason);
            }
            return (T) blobs;
        } else {
            return (T) new Blob(IOUtils.copyToTempFile(value.byteStream()));
        }
    }
    String nuxeoEntity = mediaType.nuxeoEntity();
    // Checking the type of the method clientside - aka object for Automation calls.
    if (javaType.getRawClass().equals(Object.class)) {
        if (nuxeoEntity != null) {
            switch (nuxeoEntity) {
            case ConstantsV1.ENTITY_TYPE_DOCUMENT:
                return (T) readJSON(value.charStream(), Document.class);
            case ConstantsV1.ENTITY_TYPE_DOCUMENTS:
                return (T) readJSON(value.charStream(), Documents.class);
            default:
                return (T) value;
            }
        } else {
            // This workaround is only for recordsets. There is not
            // header nuxeo-entity set for now serverside.
            String response = value.string();
            Object objectResponse = readJSON(response, Object.class);
            switch ((String) ((Map<String, Object>) objectResponse).get(ConstantsV1.ENTITY_TYPE)) {
            case ConstantsV1.ENTITY_TYPE_RECORDSET:
                return (T) readJSON(response, RecordSet.class);
            default:
                return (T) value;
            }
        }
    }
    Reader reader = value.charStream();
    try {
        return adapter.readValue(reader);
    } catch (IOException reason) {
        throw new NuxeoClientException(reason);
    } finally {
        closeQuietly(reader);
    }
}

From source file:org.openhim.mediator.normalization.XDSbMimeProcessorActor.java

private void parseMimeMessage(String msg, String contentType)
        throws IOException, MessagingException, SOAPPartNotFound, UnprocessableContentFound {
    mimeMessage = new MimeMultipart(new ByteArrayDataSource(msg, contentType));
    for (int i = 0; i < mimeMessage.getCount(); i++) {
        BodyPart part = mimeMessage.getBodyPart(i);

        if (part.getContentType().contains("application/soap+xml")) {
            _soapPart = getValue(part);/*from  w w  w. ja  va  2  s  .c o  m*/
        } else {
            _documents.add(getValue(part));
        }
    }

    if (_soapPart == null) {
        throw new SOAPPartNotFound();
    }
}

From source file:com.googlecode.psiprobe.tools.Mailer.java

private MimeMessage createMimeMessage(Session session, MailMessage mailMessage) throws MessagingException {
    InternetAddress[] to = createAddresses(mailMessage.getToArray());
    InternetAddress[] cc = createAddresses(mailMessage.getCcArray());
    InternetAddress[] bcc = createAddresses(mailMessage.getBccArray());
    if (to.length == 0) {
        to = InternetAddress.parse(defaultTo);
    }/*from   w  ww .ja v a2s . c o  m*/

    String subject = mailMessage.getSubject();
    if (subjectPrefix != null && !subjectPrefix.equals("")) {
        subject = subjectPrefix + " " + subject;
    }

    MimeMultipart content = new MimeMultipart("related");

    //Create attachments
    DataSource[] attachments = mailMessage.getAttachmentsArray();
    for (int i = 0; i < attachments.length; i++) {
        DataSource attachment = attachments[i];
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);
        content.addBodyPart(attachmentPart);
    }

    //Create message body
    MimeBodyPart bodyPart = createMessageBodyPart(mailMessage.getBody(), mailMessage.isBodyHtml());
    content.addBodyPart(bodyPart);

    MimeMessage message = new MimeMessage(session);
    if (from == null) {
        message.setFrom(); //Uses mail.from property
    } else {
        message.setFrom(new InternetAddress(from));
    }
    message.setRecipients(Message.RecipientType.TO, to);
    message.setRecipients(Message.RecipientType.CC, cc);
    message.setRecipients(Message.RecipientType.BCC, bcc);
    message.setSubject(subject);
    message.setContent(content);
    return message;
}

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

private MimeMessage prepareHTMLMimeMessage(InternetAddress internetAddressFrom, String subject, String htmlBody,
        List<LabelValueBean> attachments) throws Exception {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(internetAddressFrom);/*  w w  w . j  a  va  2 s .c  o  m*/
    msg.setHeader(XMAILER, xmailer);
    msg.setSubject(subject.trim(), mailEncoding);
    msg.setSentDate(new Date());

    MimeMultipart mimeMultipart = new MimeMultipart("related");

    BodyPart messageBodyPart = new MimeBodyPart();
    //Euro sign finally, shown correctly
    messageBodyPart.setContent(htmlBody, "text/html;charset=" + mailEncoding);
    mimeMultipart.addBodyPart(messageBodyPart);

    if (attachments != null && !attachments.isEmpty()) {
        LOGGER.debug("Use attachments: " + attachments.size());
        includeAttachments(mimeMultipart, attachments);
    }

    msg.setContent(mimeMultipart);

    return msg;
}

From source file:org.nuxeo.ecm.automation.jaxrs.io.operations.MultiPartRequestReader.java

@Override
public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;//from   w w w .  ja  va2s .  c om
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = Framework.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        in = new SharedFileInputStream(tmp); // get the input from the saved
        // file
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            JsonParser jp = factory.createJsonParser(pin);
            req = JsonRequestReader.readRequest(jp, headers, getCoreSession());
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw WebException.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            tmp.delete();
        }
    } catch (MessagingException | IOException e) {
        throw WebException.newException("Failed to parse multipart request", e);
    }
    return req;
}

From source file:org.nuxeo.ecm.automation.jaxrs.io.operations.MultiPartFormRequestReader.java

@Override
public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;/*  www.  j  a va 2 s.c o  m*/
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = Framework.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        // get the input from the saved file
        in = new SharedFileInputStream(tmp);
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            JsonParser jp = factory.createJsonParser(pin);
            req = JsonRequestReader.readRequest(jp, headers, getCoreSession());
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw WebException.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // do nothing
            }
            tmp.delete();
        }
    } catch (MessagingException | IOException e) {
        throw WebException.newException("Failed to parse multipart request", e);
    }
    return req;
}

From source file:net.sourceforge.subsonic.backend.service.EmailSession.java

public void sendHtmlMessage(String from, List<String> to, List<String> cc, List<String> bcc,
        List<String> replyTo, String subject, String html, String plain) throws MessagingException {
    MimeMessage message = createMessage(from, to, cc, bcc, replyTo, subject);

    MimeBodyPart plainPart = new MimeBodyPart();
    plainPart.setText(plain);//from ww  w .j a  v  a  2 s.  c  o m

    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setText(html, "utf-8", "html");

    MimeMultipart multipart = new MimeMultipart("alternative");
    multipart.addBodyPart(plainPart);
    multipart.addBodyPart(htmlPart);
    message.setContent(multipart);

    sendMessage(message);
}

From source file:com.caris.oscarexchange4j.proxy.PreviewCoverage.java

@Override
public void processInputStream(InputStream is) throws Exception {
    try {// w ww  .j av a2  s  .co m
        MimeMultipart multiPart = new MimeMultipart(new ByteArrayDataSource(is, MULTI_PART_MIME_TYPE));
        int count = multiPart.getCount();
        for (int part = 0; part < count; part++) {
            BodyPart body = multiPart.getBodyPart(part);
            if (body.isMimeType(OUTPUT_MIME_TYPE)) {
                this.inputStream = body.getInputStream();
                break;
            }
        }
    } catch (Exception e) {
        this.inputStream = getErrorResponseStream();
    }
}

From source file:com.adaptris.util.text.mime.ByteArrayIterator.java

@Override
protected void initIterator() throws MessagingException, IOException {
    bodyParts = new Vector<BytePartHolder>();
    MimeMultipart multipart = new MimeMultipart(dataSource);
    for (int i = 0; i < multipart.getCount(); i++) {
        MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(i);
        BytePartHolder ph = new BytePartHolder(part);
        if (bodyParts.contains(ph)) {
            log.warn("{} already exists as a part", ph.contentId);
        }// w  ww. ja v a 2  s  .c om
        bodyParts.add(ph);
    }
    bodyPartIterator = bodyParts.iterator();
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private void sendMessage(final String content) {
    try {/*  w w w . ja  v a2  s . co  m*/
        MimeMessage msg = new MimeMessage(sessionProvider.get());
        msg.setSubject("jFunk E-mail Report");
        msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get());

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=UTF-8");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif")));
        messageBodyPart.setHeader("Content-ID", "<check>");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif")));
        messageBodyPart.setHeader("Content-ID", "<error>");
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);

        smtpClientProvider.get().send(msg);

        int anzahlRecipients = msg.getAllRecipients().length;
        log.info(
                "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get());
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    } catch (MailException e) {
        log.error("Error while sending report e-mail", e);
    }
}