Example usage for javax.mail.internet MimeBodyPart setContentID

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

Introduction

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

Prototype

public void setContentID(String cid) throws MessagingException 

Source Link

Document

Set the "Content-ID" header field of this body part.

Usage

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

public static boolean prepareRequestPart(WsdlRequest wsdlRequest, MimeMultipart mp, RequestXmlPart requestPart,
        StringToStringMap contentIds) throws Exception, MessagingException {
    boolean isXop = false;

    XmlCursor cursor = requestPart.newCursor();

    try {//from   ww  w .  ja va  2s .  c o  m
        while (!cursor.isEnddoc()) {
            if (cursor.isContainer()) {
                // could be an attachment part (as of "old" SwA specs which specify a content 
                // element referring to the attachment)
                if (requestPart.isAttachmentPart()) {
                    String href = cursor.getAttributeText(new QName("href"));
                    if (href != null && href.length() > 0) {
                        contentIds.put(requestPart.getPart().getName(), href);
                    }

                    break;
                }

                SchemaType schemaType = cursor.getObject().schemaType();
                if (isBinaryType(schemaType)) {
                    String contentType = getXmlMimeContentType(cursor);

                    // extract contentId
                    String textContent = cursor.getTextValue();
                    Attachment attachment = null;
                    boolean isXopAttachment = false;

                    // is content a reference to a file?
                    if (textContent.startsWith("file:")) {
                        String filename = textContent.substring(5);
                        if (contentType == null) {
                            inlineData(cursor, schemaType, new FileInputStream(filename));
                        } else if (wsdlRequest.isMtomEnabled()) {
                            MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                            part.setDataHandler(new DataHandler(
                                    new XOPPartDataSource(new File(filename), contentType, schemaType)));
                            part.setContentID("<" + filename + ">");
                            mp.addBodyPart(part);

                            isXopAttachment = true;
                        }
                    }
                    // is content a reference to an attachment?
                    else if (textContent.startsWith("cid:")) {
                        textContent = textContent.substring(4);
                        Attachment[] attachments = wsdlRequest.getAttachmentsForPart(textContent);
                        if (attachments.length == 1) {
                            attachment = attachments[0];
                        } else if (attachments.length > 1) {
                            attachment = buildMulitpartAttachment(attachments);
                        }

                        isXopAttachment = contentType != null;
                        contentIds.put(textContent, textContent);
                    }
                    // content should be binary data; is this an XOP element which should be serialized with MTOM?
                    else if (wsdlRequest.isMtomEnabled() && contentType != null) {
                        MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                        part.setDataHandler(
                                new DataHandler(new XOPPartDataSource(textContent, contentType, schemaType)));

                        textContent = "http://www.soapui.org/" + System.nanoTime();

                        part.setContentID("<" + textContent + ">");
                        mp.addBodyPart(part);

                        isXopAttachment = true;
                    }

                    // add XOP include?
                    if (isXopAttachment && wsdlRequest.isMtomEnabled()) {
                        buildXopInclude(cursor, textContent);
                        isXop = true;
                    }
                    // inline?
                    else if (attachment != null) {
                        inlineAttachment(cursor, schemaType, attachment);
                    }
                }
            }

            cursor.toNextToken();
        }
    } finally {
        cursor.dispose();
    }

    return isXop;
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

public static void initPartContentId(StringToStringMap contentIds, MimeBodyPart part, Attachment attachment,
        boolean isMultipart) throws MessagingException {
    String partName = attachment.getPart();

    String contentID = attachment.getContentID();
    if (StringUtils.hasContent(contentID)) {
        contentID = contentID.trim();//from  w w w. j av  a 2 s .co  m
        int ix = contentID.indexOf(' ');
        if (ix != -1)
            part.setContentID(
                    "<" + (isMultipart ? contentID.substring(ix + 1) : contentID.substring(0, ix)) + ">");
        else {
            if (!contentID.startsWith("<"))
                contentID = "<" + contentID;

            if (!contentID.endsWith(">"))
                contentID = contentID + ">";

            part.setContentID(contentID);
        }
    } else if (partName != null && !partName.equals(HttpAttachmentPart.ANONYMOUS_NAME)) {
        if (contentIds.containsKey(partName)) {
            part.setContentID("<" + contentIds.get(partName) + ">");
        } else {
            part.setContentID("<" + partName + "=" + System.nanoTime() + "@soapui.org>");
        }
    }

    // set content-disposition
    String name = attachment.getName();
    String file = attachment.getUrl();
    if (PathUtils.isFilePath(file)) {
        int ix = file.lastIndexOf(File.separatorChar);
        if (ix == -1)
            ix = file.lastIndexOf('/');

        if (ix > 0 && ix < file.length() - 1)
            file = file.substring(ix + 1);

        part.setDisposition("attachment; name=\"" + name + "\"; filename=\"" + file + "\"");
    } else {
        part.setDisposition("attachment; name=\"" + name + "\"");
    }
}

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

public void setRequest(String content) throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();
    part.setText(content, "UTF-8");
    part.setContentID("request");
    part.setHeader("Content-Type", Constants.CTYPE_REQUEST);
    part.setHeader("Content-Transfer-Encoding", "8bit");
    part.setHeader("Content-Length", Integer.toString(content.length()));
    mp.addBodyPart(part);/*w  w  w. j  a v  a  2 s .c  o  m*/
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.WsdlPackagingRequestFilter.java

/**
 * Creates root BodyPart containing message
 *///from ww w. j  a va2  s .c om

protected void initRootPart(WsdlRequest wsdlRequest, String requestContent, MimeMultipart mp, boolean isXOP)
        throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart(System.getProperty("soapui.bodypart.encoding", "8bit"));
    rootPart.setContentID(AttachmentUtils.ROOTPART_SOAPUI_ORG);
    mp.addBodyPart(rootPart, 0);

    DataHandler dataHandler = new DataHandler(new WsdlRequestDataSource(wsdlRequest, requestContent, isXOP));
    rootPart.setDataHandler(dataHandler);
}

From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java

protected void visitNode(Map cache, Node node, MimeMultipart multipart) throws Exception {

    ModelItem item = (ModelItem) node.getUserData("");
    if (item != null && item.getDeclarationView().getDatatype() != null
            && item.getDeclarationView().getDatatype().equalsIgnoreCase("anyURI")) {
        String name = item.getFilename();
        if (name == null || item.getValue() == null || item.getValue().equals("")) {
            return;
        }/*www .  j a v  a2  s.  c om*/

        String cid = (String) cache.get(name);
        if (cid == null) {
            int count = multipart.getCount();
            cid = name + "@part" + (count + 1);

            MimeBodyPart part = new MimeBodyPart();
            part.setContentID("<" + cid + ">");

            DataHandler dh = new DataHandler(new ModelItemDataSource(item));
            part.setDataHandler(dh);

            part.addHeader("Content-Type", item.getMediatype());
            part.addHeader("Content-Transfer-Encoding", "base64");
            part.setDisposition("attachment");
            part.setFileName(name);
            multipart.addBodyPart(part);
            cache.put(name, cid);
        }

        Element element = (Element) node;
        // remove text node
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() != Node.TEXT_NODE) {
                continue;
            }
            n.setNodeValue("cid:" + cid);
            break;
        }
    } else {
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                visitNode(cache, n, multipart);
            }
        }
    }
}

From source file:it.ozimov.springboot.templating.mail.service.EmailServiceImpl.java

public MimeMessage send(final @NonNull Email email, final @NonNull String template,
        final Map<String, Object> modelObject, final @NonNull InlinePicture... inlinePictures)
        throws CannotSendEmailException {
    email.setSentAt(new Date());
    final MimeMessage mimeMessage = toMimeMessage(email);
    try {/*ww w .  j av  a  2s.c o  m*/
        final MimeMultipart content = new MimeMultipart("related");

        String text = templateService.mergeTemplateIntoString(template,
                fromNullable(modelObject).or(ImmutableMap.of()));

        for (final InlinePicture inlinePicture : inlinePictures) {
            final String cid = UUID.randomUUID().toString();

            //Set the cid in the template
            text = text.replace(inlinePicture.getTemplateName(), "cid:" + cid);

            //Set the image part
            final MimeBodyPart imagePart = new MimeBodyPart();
            imagePart.attachFile(inlinePicture.getFile());
            imagePart.setContentID('<' + cid + '>');
            imagePart.setDisposition(MimeBodyPart.INLINE);
            imagePart.setHeader("Content-Type", inlinePicture.getImageType().getContentType());
            content.addBodyPart(imagePart);
        }

        //Set the HTML text part
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(text, email.getEncoding().displayName(), "html");
        content.addBodyPart(textPart);

        mimeMessage.setContent(content);
        javaMailSender.send(mimeMessage);
    } catch (IOException e) {
        log.error("The template file cannot be read", e);
        throw new CannotSendEmailException(
                "Error while sending the email due to problems with the template file", e);
    } catch (TemplateException e) {
        log.error("The template file cannot be processed", e);
        throw new CannotSendEmailException(
                "Error while processing the template file with the given model object", e);
    } catch (MessagingException e) {
        log.error("The mime message cannot be created", e);
        throw new CannotSendEmailException(
                "Error while sending the email due to problems with the mime content", e);
    }
    return mimeMessage;
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

public static boolean prepareMessagePart(WsdlAttachmentContainer container, MimeMultipart mp,
        MessageXmlPart messagePart, StringToStringMap contentIds) throws Exception, MessagingException {
    boolean isXop = false;

    XmlObjectTreeModel treeModel = null;
    XmlCursor cursor = messagePart.newCursor();
    XmlObject rootXmlObject = cursor.getObject();

    try {//from   www.  jav  a 2 s  .  c om
        while (!cursor.isEnddoc()) {
            if (cursor.isContainer()) {
                // could be an attachment part (as of "old" SwA specs which
                // specify a content
                // element referring to the attachment)
                if (messagePart.isAttachmentPart()) {
                    String href = cursor.getAttributeText(XOP_HREF_QNAME);
                    if (href != null && href.length() > 0) {
                        contentIds.put(messagePart.getPart().getName(), href);
                    }

                    break;
                }

                XmlObject xmlObj = cursor.getObject();
                SchemaType schemaType = xmlObj.schemaType();
                if (schemaType.isNoType()) {
                    if (treeModel == null) {
                        treeModel = new XmlObjectTreeModel(messagePart.getSchemaType().getTypeSystem(),
                                rootXmlObject);
                    }

                    XmlTreeNode tn = treeModel.getXmlTreeNode(xmlObj);
                    if (tn != null)
                        schemaType = tn.getSchemaType();
                }

                if (AttachmentUtils.isSwaRefType(schemaType)) {
                    String textContent = XmlUtils.getNodeValue(cursor.getDomNode());
                    if (StringUtils.hasContent(textContent) && textContent.startsWith("cid:")) {
                        textContent = textContent.substring(4);

                        try {
                            // is the textcontent already a URI?
                            new URI(textContent);
                            contentIds.put(textContent, textContent);
                        } catch (RuntimeException e) {
                            // not a URI.. try to create one..
                            String contentId = textContent + "@soapui.org";
                            cursor.setTextValue("cid:" + contentId);
                            contentIds.put(textContent, contentId);
                        }
                    }
                } else if (AttachmentUtils.isXopInclude(schemaType)) {
                    String contentId = cursor.getAttributeText(new QName("href"));
                    if (contentId != null && contentId.length() > 0) {
                        contentIds.put(contentId, contentId);
                        isXop = true;

                        Attachment[] attachments = container.getAttachmentsForPart(contentId);
                        if (attachments.length == 1) {
                            XmlCursor cur = cursor.newCursor();
                            if (cur.toParent()) {
                                String contentType = getXmlMimeContentType(cur);
                                if (contentType != null && contentType.length() > 0)
                                    attachments[0].setContentType(contentType);
                            }

                            cur.dispose();
                        }
                    }
                } else {
                    // extract contentId
                    String textContent = XmlUtils.getNodeValue(cursor.getDomNode());
                    if (StringUtils.hasContent(textContent)) {
                        Attachment attachment = null;
                        boolean isXopAttachment = false;

                        // is content a reference to a file?
                        if (container.isInlineFilesEnabled() && textContent.startsWith("file:")) {
                            String filename = textContent.substring(5);
                            if (container.isMtomEnabled()) {
                                MimeBodyPart part = new PreencodedMimeBodyPart("binary");
                                String xmimeContentType = getXmlMimeContentType(cursor);

                                if (StringUtils.isNullOrEmpty(xmimeContentType))
                                    xmimeContentType = ContentTypeHandler.getContentTypeFromFilename(filename);

                                part.setDataHandler(new DataHandler(new XOPPartDataSource(new File(filename),
                                        xmimeContentType, schemaType)));
                                part.setContentID("<" + filename + ">");
                                mp.addBodyPart(part);

                                isXopAttachment = true;
                            } else {
                                if (new File(filename).exists()) {
                                    inlineData(cursor, schemaType, new FileInputStream(filename));
                                } else {
                                    Attachment att = getAttachmentForFilename(container, filename);
                                    if (att != null)
                                        inlineData(cursor, schemaType, att.getInputStream());
                                }
                            }
                        } else {
                            Attachment[] attachmentsForPart = container.getAttachmentsForPart(textContent);
                            if (textContent.startsWith("cid:")) {
                                textContent = textContent.substring(4);
                                attachmentsForPart = container.getAttachmentsForPart(textContent);

                                Attachment[] attachments = attachmentsForPart;
                                if (attachments.length == 1) {
                                    attachment = attachments[0];
                                } else if (attachments.length > 1) {
                                    attachment = buildMulitpartAttachment(attachments);
                                }

                                isXopAttachment = container.isMtomEnabled();
                                contentIds.put(textContent, textContent);
                            }
                            // content should be binary data; is this an XOP element
                            // which should be serialized with MTOM?
                            else if (container.isMtomEnabled() && (SchemaUtils.isBinaryType(schemaType)
                                    || SchemaUtils.isAnyType(schemaType))) {
                                if ("true".equals(System.getProperty("soapui.mtom.strict"))) {
                                    if (SchemaUtils.isAnyType(schemaType)) {
                                        textContent = null;
                                    } else {
                                        for (int c = 0; c < textContent.length(); c++) {
                                            if (Character.isWhitespace(textContent.charAt(c))) {
                                                textContent = null;
                                                break;
                                            }
                                        }
                                    }
                                }

                                if (textContent != null) {
                                    MimeBodyPart part = new PreencodedMimeBodyPart("binary");
                                    String xmimeContentType = getXmlMimeContentType(cursor);

                                    part.setDataHandler(new DataHandler(
                                            new XOPPartDataSource(textContent, xmimeContentType, schemaType)));

                                    textContent = "http://www.soapui.org/" + System.nanoTime();

                                    part.setContentID("<" + textContent + ">");
                                    mp.addBodyPart(part);

                                    isXopAttachment = true;
                                }
                            } else if (container.isInlineFilesEnabled() && attachmentsForPart != null
                                    && attachmentsForPart.length > 0) {
                                attachment = attachmentsForPart[0];
                            }
                        }

                        // add XOP include?
                        if (isXopAttachment && container.isMtomEnabled()) {
                            buildXopInclude(cursor, textContent);
                            isXop = true;
                        }
                        // inline?
                        else if (attachment != null) {
                            inlineAttachment(cursor, schemaType, attachment);
                        }
                    }
                }
            }

            cursor.toNextToken();
        }
    } finally {
        cursor.dispose();
    }

    return isXop;
}

From source file:com.threewks.thundr.mail.JavaMailMailer.java

private void addAttachments(Multipart multipart, List<Attachment> attachments) throws MessagingException {
    for (Attachment attachment : attachments) {
        BasicViewRenderer response = render(attachment.view());
        byte[] base64Encoded = Base64.encodeToByte(response.getOutputAsBytes());

        InternetHeaders headers = new InternetHeaders();
        headers.addHeader(Header.ContentType, response.getContentType());
        headers.addHeader(Header.ContentTransferEncoding, "base64");

        MimeBodyPart part = new MimeBodyPart(headers, base64Encoded);
        part.setFileName(attachment.name());
        part.setDisposition(attachment.disposition().value());

        if (attachment.isInline()) {
            part.setContentID(attachment.contentId());
        }/*from  w  w  w.  j  a va  2s . c  o m*/

        multipart.addBodyPart(part);
    }
}

From source file:com.eviware.soapui.impl.support.AbstractMockResponse.java

private void initRootPart(String requestContent, MimeMultipart mp, boolean isXOP) throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart("8bit");
    rootPart.setContentID(AttachmentUtils.ROOTPART_SOAPUI_ORG);
    mp.addBodyPart(rootPart, 0);/* w  ww.j  a v  a 2 s.c o  m*/

    DataHandler dataHandler = new DataHandler(new MockResponseDataSource(this, requestContent, isXOP));
    rootPart.setDataHandler(dataHandler);
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeBodyPart????Content-Disposition: inline
 *
 * @param file//  www. j  ava2  s .c  o  m
 *            ?
 * @return MimeBodyPartContent-Disposition: inline?
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private MimeBodyPart createImagePart(InlineImageFile file)
        throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart imagePart = new MimeBodyPart();
    imagePart.setContentID(file.getContentId());
    imagePart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
    imagePart.setDataHandler(new DataHandler(file.getDataSource()));
    imagePart.setDisposition(MimeBodyPart.INLINE);
    return imagePart;
}