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.mule.service.http.impl.service.server.grizzly.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;//from  w  w  w .j a  va 2s .c  o  m
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }

            if (partName == null && mimeMultipart.getContentType().contains(MULTIPART_RELATED.toString())) {
                String[] contentIdHeader = part.getHeader(CONTENT_ID);
                if (contentIdHeader != null && contentIdHeader.length > 0) {
                    partName = contentIdHeader[0];
                }
            }

            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

From source file:org.mule.module.http.internal.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;/*  w  w  w.  j ava 2  s.c om*/
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION_PART_HEADER);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }
            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

From source file:nz.co.testamation.common.mail.MultipartMessageFactoryImpl.java

@Override
public Multipart create(Email email) throws MessagingException {
    Multipart multipart = isNotBlank(email.getHtmlBody()) ? new MimeMultipart("alternative")
            : new MimeMultipart();

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(StringUtil.toNotNullString(email.getTextBody()));
    multipart.addBodyPart(textPart);/*w  ww.  ja v a 2s  . c o m*/

    if (isNotBlank(email.getHtmlBody())) {
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(email.getHtmlBody(), "text/html");
        multipart.addBodyPart(htmlPart);
    }

    if (email.getAttachments() != null) {
        for (EmailAttachment attachment : email.getAttachments()) {
            multipart.addBodyPart(attachmentBodyPartFactory.create(attachment));
        }
    }
    return multipart;
}

From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.MultipartRequestEntity.java

public MultipartRequestEntity() {
    this(new MimeMultipart("related"));
}

From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.MultipartRequestEntity.java

public MultipartRequestEntity(String subType) {
    this(new MimeMultipart(subType));
}

From source file:org.apache.axis.encoding.ser.MimeMultipartDataHandlerDeserializer.java

public void startElement(String namespace, String localName, String prefix, Attributes attributes,
        DeserializationContext context) throws SAXException {

    super.startElement(namespace, localName, prefix, attributes, context);

    if (getValue() instanceof DataHandler) {
        try {/*from w ww.  j  a  v  a  2  s  .c  o m*/
            DataHandler dh = (DataHandler) getValue();
            MimeMultipart mmp = new MimeMultipart(dh.getDataSource());
            if (mmp.getCount() == 0) {
                mmp = null;
            }
            setValue(mmp);
        } catch (Exception e) {
            throw new SAXException(e);
        }
    }
}

From source file:com.mirth.connect.server.userutil.HTTPUtil.java

/**
 * Serializes an HTTP request body into XML. Multipart requests will also automatically be
 * parsed into separate XML nodes./*from ww  w. ja  va2 s  . c o m*/
 * 
 * @param httpBody
 *            The request body/payload input stream to parse.
 * @param contentType
 *            The MIME content type of the request.
 * @return The serialized XML string.
 * @throws MessagingException
 * @throws IOException
 * @throws DonkeyElementException
 * @throws ParserConfigurationException
 */
public static String httpBodyToXml(InputStream httpBody, String contentType)
        throws MessagingException, IOException, DonkeyElementException, ParserConfigurationException {
    ContentType type = getContentType(contentType);
    Object content;

    if (type.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
        content = new MimeMultipart(new ByteArrayDataSource(httpBody, type.toString()));
    } else {
        content = IOUtils.toString(httpBody,
                HttpMessageConverter.getDefaultHttpCharset(type.getCharset().name()));
    }

    return HttpMessageConverter.contentToXml(content, type, true, null);
}

From source file:com.email.SendEmailCalInvite.java

/**
 * Sends email based off of the section it comes from. This creates a
 * calendar invite object that is interactive by Outlook.
 *
 * @param eml EmailOutInviteModel/* w w w  .  java 2 s .co  m*/
 */
public static void sendCalendarInvite(EmailOutInvitesModel eml) {
    SystemEmailModel account = null;

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(eml.getSection())) {
            account = acc;
            break;
        }
    }
    if (account != null) {
        //Get parts
        String FromAddress = account.getEmailAddress();
        String[] TOAddressess = ((eml.getToAddress() == null) ? "".split(";") : eml.getToAddress().split(";"));
        String[] CCAddressess = ((eml.getCcAddress() == null) ? "".split(";") : eml.getCcAddress().split(";"));
        String emailSubject = "";
        BodyPart emailBody = body(eml);
        BodyPart inviteBody = null;

        if (eml.getHearingRoomAbv() == null) {
            emailSubject = eml.getEmailSubject() == null
                    ? (eml.getEmailBody() == null ? eml.getCaseNumber() : eml.getEmailBody())
                    : eml.getEmailSubject();
            inviteBody = responseDueCalObject(eml, account);
        } else {
            emailSubject = eml.getEmailSubject() == null ? Subject(eml) : eml.getEmailSubject();
            inviteBody = inviteCalObject(eml, account, emailSubject);
        }

        //Set Email Parts
        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);
        Session session = Session.getInstance(properties, auth);
        MimeMessage smessage = new MimeMessage(session);
        Multipart multipart = new MimeMultipart("alternative");
        try {
            smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
            for (String To : TOAddressess) {
                if (EmailValidator.getInstance().isValid(To)) {
                    smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                }
            }
            for (String Cc : CCAddressess) {
                if (EmailValidator.getInstance().isValid(Cc)) {
                    smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(Cc));
                }
            }
            smessage.setSubject(emailSubject);
            multipart.addBodyPart(emailBody);
            multipart.addBodyPart(inviteBody);
            smessage.setContent(multipart);
            if (Global.isOkToSendEmail()) {
                Transport.send(smessage);
            } else {
                Audit.addAuditEntry("Cal Invite Not Actually Sent: " + eml.getId() + " - " + emailSubject);
            }
            EmailOutInvites.deleteEmailEntry(eml.getId());
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.MimeMessageResponse.java

public MimeMessageResponse(WsdlRequest wsdlRequest, final TimeablePostMethod postMethod,
        String requestContent) {/*from   ww  w  . j a  v a 2s. c  o  m*/
    this.wsdlRequest = wsdlRequest;
    this.requestContent = requestContent;
    this.timeTaken = postMethod.getTimeTaken();
    responseContentLength = postMethod.getResponseContentLength();

    try {
        initHeaders(postMethod);

        MimeMultipart mp = new MimeMultipart(new PostResponseDataSource(postMethod));
        message = new MimeMessage(HttpClientRequestTransport.JAVAMAIL_SESSION);
        message.setContent(mp);

        Header h = postMethod.getResponseHeader("Content-Type");
        HeaderElement[] elements = h.getElements();

        String rootPartId = null;

        for (HeaderElement element : elements) {
            if (element.getName().toUpperCase().startsWith("MULTIPART/")) {
                NameValuePair parameter = element.getParameterByName("start");
                if (parameter != null)
                    rootPartId = parameter.getValue();
            }
        }

        for (int c = 0; c < mp.getCount(); c++) {
            BodyPart bodyPart = mp.getBodyPart(c);

            if (bodyPart.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                MimeMultipart mp2 = new MimeMultipart(new BodyPartDataSource(bodyPart));
                for (int i = 0; i < mp2.getCount(); i++) {
                    result.add(new BodyPartAttachment(mp2.getBodyPart(i)));
                }
            } else {
                BodyPartAttachment attachment = new BodyPartAttachment(bodyPart);

                String[] contentIdHeaders = bodyPart.getHeader("Content-ID");
                if (contentIdHeaders != null && contentIdHeaders.length > 0
                        && contentIdHeaders[0].equals(rootPartId)) {
                    rootPart = attachment;
                } else
                    result.add(attachment);
            }
        }

        // if no explicit root part has been set, use the first one in the result
        if (rootPart == null)
            rootPart = result.remove(0);

        if (wsdlRequest.getSettings().getBoolean(HttpSettings.INCLUDE_RESPONSE_IN_TIME_TAKEN))
            this.timeTaken = postMethod.getTimeTakenUntilNow();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.mule.transport.email.transformers.ObjectToMimeMessage.java

@Override
protected void setContent(Object payload, Message msg, String contentType, MuleMessage message)
        throws Exception {
    boolean transformInboundAttachments = useInboundAttachments
            && message.getInboundAttachmentNames().size() > 0;
    boolean transformOutboundAttachments = useOutboundAttachments
            && message.getOutboundAttachmentNames().size() > 0;
    if (transformInboundAttachments || transformOutboundAttachments) {
        // The content type must be multipart/mixed
        MimeMultipart multipart = new MimeMultipart("mixed");
        multipart.addBodyPart(getPayloadBodyPart(message.getPayload(), contentType));
        if (transformInboundAttachments) {
            for (String name : message.getInboundAttachmentNames()) {
                // Let outbound attachments override inbound ones
                if (!transformOutboundAttachments || message.getOutboundAttachment(name) == null) {
                    BodyPart part = getBodyPartForAttachment(message.getInboundAttachment(name), name);
                    // Check message props for extra headers
                    addBodyPartHeaders(part, name, message);
                    multipart.addBodyPart(part);
                }//from w  ww  .j  ava 2 s. co m
            }
        }
        if (transformOutboundAttachments) {
            for (String name : message.getOutboundAttachmentNames()) {
                BodyPart part = getBodyPartForAttachment(message.getOutboundAttachment(name), name);
                // Check message props for extra headers
                addBodyPartHeaders(part, name, message);
                multipart.addBodyPart(part);
            }
        }
        // the payload must be set to the constructed MimeMultipart message
        payload = multipart;
        // the ContentType of the message to be sent, must be the multipart content type
        contentType = multipart.getContentType();
    }

    // now the message will contain the multipart payload, and the multipart
    // contentType
    super.setContent(payload, msg, contentType, message);
}