Example usage for javax.mail Part getDisposition

List of usage examples for javax.mail Part getDisposition

Introduction

In this page you can find the example usage for javax.mail Part getDisposition.

Prototype

public String getDisposition() throws MessagingException;

Source Link

Document

Return the disposition of this part.

Usage

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

private boolean isAttachAndNotInline(Part part) throws MessagingException {
    return (part.getDisposition() != null && part.getDisposition().equals(Part.ATTACHMENT));
}

From source file:com.stimulus.archiva.domain.Email.java

protected boolean hasAttachment(Part p) throws MessagingException, IOException {

    if (p.getDisposition() != null && Compare.equalsIgnoreCase(p.getDisposition(), Part.ATTACHMENT)) {
        logger.debug("hasAttachment() attachment disposition.");
        return true;
    }//  w w w.j  ava2 s  . co  m
    if (p.getFileName() != null) {
        logger.debug("hasAttachment() filename specified.");
        return true;
    }

    try {
        if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                logger.debug("hasAttachment() scanning multipart[" + i + "]");
                if (hasAttachment(mp.getBodyPart(i)))
                    return true;
            }
        } else if (p.isMimeType("message/rfc822")) {
            return hasAttachment((Part) p.getContent());
        }
    } catch (Exception e) {
        logger.debug("exception occurred while detecting attachment", e);
    }
    return false;
}

From source file:org.apache.axis2.transport.mail.SimpleMailListener.java

private void buildSOAPEnvelope(MimeMessage msg, MessageContext msgContext) throws AxisFault {
    //TODO we assume for the time being that there is only one attachement and this attachement contains  the soap evelope
    try {/*from   www  . jav a2  s  .  c  om*/
        Multipart mp = (Multipart) msg.getContent();
        if (mp != null) {
            for (int i = 0, n = mp.getCount(); i < n; i++) {
                Part part = mp.getBodyPart(i);

                String disposition = part.getDisposition();

                if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
                    String soapAction;

                    /* Set the Charactorset Encoding */
                    String contentType = part.getContentType();
                    String charSetEncoding = BuilderUtil.getCharSetEncoding(contentType);
                    if (charSetEncoding != null) {
                        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                                charSetEncoding);
                    } else {
                        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                                MessageContext.DEFAULT_CHAR_SET_ENCODING);
                    }

                    /* SOAP Action */
                    soapAction = getMailHeaderFromPart(part,
                            org.apache.axis2.transport.mail.Constants.HEADER_SOAP_ACTION);
                    msgContext.setSoapAction(soapAction);

                    String contentDescription = getMailHeaderFromPart(part, "Content-Description");

                    /* As an input stream - using the getInputStream() method.
                    Any mail-specific encodings are decoded before this stream is returned.*/
                    if (contentDescription != null) {
                        msgContext.setTo(new EndpointReference(contentDescription));
                    }

                    if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
                        TransportUtils.processContentTypeForAction(contentType, msgContext);
                    } else {
                        // According to the mail sepec, mail transport should support only
                        // application/soap+xml;
                        String message = "According to the mail sepec, mail transport "
                                + "should support only application/soap+xml";
                        log.error(message);
                        throw new AxisFault(message);
                    }

                    String cte = getMailHeaderFromPart(part, "Content-Transfer-Encoding");
                    if (!(cte != null && cte.equalsIgnoreCase("base64"))) {
                        String message = "Processing of Content-Transfer-Encoding faild.";
                        log.error(message);
                        throw new AxisFault(message);
                    }
                    InputStream inputStream = part.getInputStream();
                    SOAPEnvelope envelope = TransportUtils.createSOAPMessage(msgContext, inputStream,
                            contentType);
                    msgContext.setEnvelope(envelope);
                }
            }

        }
    } catch (IOException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (XMLStreamException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

From source file:com.szmslab.quickjavamail.receive.MessageLoader.java

/**
 * ?????MessageContent????//from  w  w w. j  av  a  2s  .c om
 *
 * @param multiPart
 *            ?
 * @param msgContent
 *            ????
 * @throws MessagingException
 * @throws IOException
 */
private void setMultipartContent(Multipart multiPart, MessageContent msgContent)
        throws MessagingException, IOException {
    for (int i = 0; i < multiPart.getCount(); i++) {
        Part part = multiPart.getBodyPart(i);
        if (part.getContentType().indexOf("multipart") >= 0) {
            setMultipartContent((Multipart) part.getContent(), msgContent);
        } else {
            String disposition = part.getDisposition();
            if (Part.ATTACHMENT.equals(disposition)) {
                // Disposition?"attachment"???ContentType????
                msgContent.attachmentFileList.add(new AttachmentFile(MimeUtility.decodeText(part.getFileName()),
                        part.getDataHandler().getDataSource()));
            } else {
                if (part.isMimeType("text/html")) {
                    msgContent.html = part.getContent().toString();
                } else if (part.isMimeType("text/plain")) {
                    msgContent.text = part.getContent().toString();
                } else {
                    // Disposition?"inline"???ContentType??
                    if (Part.INLINE.equals(disposition)) {
                        String cid = "";
                        if (part instanceof MimeBodyPart) {
                            MimeBodyPart mimePart = (MimeBodyPart) part;
                            cid = mimePart.getContentID();
                        }
                        msgContent.inlineImageFileList
                                .add(new InlineImageFile(cid, MimeUtility.decodeText(part.getFileName()),
                                        part.getDataHandler().getDataSource()));
                    }
                }
            }
        }
    }
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * @param part/*from   w w  w .j  a  va 2s  .  co m*/
 * @param attach
 * @return
 * @throws Exception
 */
private FileUtil handlePart(Part part, boolean attach) throws Exception {

    FileUtil file = null;

    String disposition = part.getDisposition();
    if (disposition == null) {
        // no nothing

    } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)) {

        file = new FileUtil();

        String fileName = part.getFileName();
        String contentType = part.getContentType();

        /* 
         * The contentType parameter contains mimetype and filename in one
         */
        String mimeType = contentType.split(";")[0].trim();

        file.setFilename(fileName);
        file.setMimetype(mimeType);

        InputStream inputStream = (attach == true) ? part.getInputStream() : null;
        if (inputStream != null)
            file.setInputStream(inputStream, mimeType);

    }

    return file;

}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Adapted extract multipart is the recusrsive parser that splits the data and apend it to the
 * final xhtml file.//from   w  ww.j  a v  a2 s  . c  o  m
 *
 * @param xhtml
 *            the xhtml
 * @param part
 *            the part
 * @param parentPart
 *            the parent part
 * @param context
 *            the context
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
public void adaptedExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart, ParseContext context)
        throws MessagingException, IOException, SAXException, TikaException {

    String disposition = part.getDisposition();
    if ((disposition != null && disposition.contains(Part.ATTACHMENT))) {
        return;
    }

    if (part.isMimeType("text/plain")) {
        if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) {
            return;
        } else {
            // add file
            String data = part.getContent().toString();
            writeContent(part, data, MimetypeMap.MIMETYPE_TEXT_PLAIN, "txt");
        }
    } else if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        Part parentPartLocal = part;
        if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) {
            parentPartLocal = parentPart;
        }
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            adaptedExtractMultipart(xhtml, mp.getBodyPart(i), parentPartLocal, context);
        }
    } else if (part.isMimeType("message/rfc822")) {
        adaptedExtractMultipart(xhtml, (Part) part.getContent(), part, context);
    } else if (part.isMimeType("text/html")) {

        if ((parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE))
                || (part.getDisposition() == null || !part.getDisposition().contains(Part.ATTACHMENT))) {
            Object data = part.getContent();
            String htmlFileData = prepareString(new String(data.toString()));
            writeContent(part, htmlFileData, MimetypeMap.MIMETYPE_HTML, "html");
        }

    } else if (part.isMimeType("image/*")) {

        String[] encoded = part.getHeader("Content-Transfer-Encoding");
        if (isContained(encoded, "base64")) {
            if (part.getDisposition() != null && part.getDisposition().contains(Part.ATTACHMENT)) {
                InputStream stream = part.getInputStream();
                byte[] binaryData = new byte[part.getSize()];
                stream.read(binaryData, 0, part.getSize());
                String encodedData = new String(Base64.encodeBase64(binaryData));
                String[] split = part.getContentType().split(";");
                String src = "data:" + split[0].trim() + ";base64," + encodedData;
                AttributesImpl attributes = new AttributesImpl();
                attributes.addAttribute(null, "src", "src", "String", src);
                xhtml.startElement("img", attributes);
                xhtml.endElement("img");
            }
        }

    } else {
        Object content = part.getContent();
        if (content instanceof String) {
            xhtml.element("div", prepareString(part.getContent().toString()));
        } else if (content instanceof InputStream) {
            InputStream fileContent = part.getInputStream();

            Parser parser = new AutoDetectParser();
            Metadata attachmentMetadata = new Metadata();

            BodyContentHandler handlerAttachments = new BodyContentHandler();
            parser.parse(fileContent, handlerAttachments, attachmentMetadata, context);

            xhtml.element("div", handlerAttachments.toString());

        }
    }
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Prepare extract multipart.// w w  w  .  j  a  v  a 2 s . c o  m
 *
 * @param xhtml
 *            the xhtml
 * @param part
 *            the part
 * @param parentPart
 *            the parent part
 * @param context
 *            the context
 * @param attachmentList
 *            is list with attachments to fill
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
private void prepareExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart,
        ParseContext context, List<String> attachmentList)
        throws MessagingException, IOException, SAXException, TikaException {

    String disposition = part.getDisposition();
    if ((disposition != null && disposition.contains(Part.ATTACHMENT))) {
        String fileName = part.getFileName();
        if (fileName != null && fileName.startsWith("=?")) {
            fileName = MimeUtility.decodeText(fileName);
        }
        attachmentList.add(fileName);
    }

    String[] header = part.getHeader("Content-ID");
    String key = null;
    if (header != null) {
        for (String string : header) {
            key = string;
        }
    }

    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            prepareExtractMultipart(xhtml, mp.getBodyPart(i), part, context, attachmentList);
        }
    } else if (part.isMimeType(MimetypeMap.MIMETYPE_RFC822)) {
        prepareExtractMultipart(xhtml, (Part) part.getContent(), part, context, attachmentList);
    } else {

        if (key == null) {
            return;
        }
        // if ((disposition != null && disposition.contains(Part.INLINE))) {
        InputStream stream = part.getInputStream();

        File file = new File(workingDirectory, System.currentTimeMillis() + "");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.copy(stream, fileOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
        String src = file.getName();
        String replace = key.replace("<", "").replace(">", "");
        referencesCache.put(replace, src);
        // }

    }
}

From source file:org.jahia.modules.gateway.mail.MailToJSONImpl.java

protected void parseMailMessage(Part part, MailContent content) throws IOException, MessagingException {
    Object mailContent = part.getContent();
    if (mailContent instanceof MimeMultipart) {
        MimeMultipart mailMessageContent = (MimeMultipart) mailContent;
        // We have some attachments
        for (int i = 0; i < mailMessageContent.getCount(); i++) {
            BodyPart bodyPart = mailMessageContent.getBodyPart(i);
            parseMailMessage(bodyPart, content);
        }/*from w w  w . j a v  a  2  s  . c o  m*/
    } else if (mailContent instanceof String && part.getDisposition() == null) {
        boolean isHtml = false;
        if (content.getBody() == null || ((isHtml = part.isMimeType("text/html")) && !content.isHtml())) {
            if (isHtml) {
                content.setBodyHtml((String) mailContent);
            } else {
                content.setBody((String) mailContent);
            }
        }
    } else if (mailContent instanceof InputStream || mailContent instanceof String) {
        File tempFile = File.createTempFile("mail2json-", null);
        try {
            FileUtils.copyInputStreamToFile(
                    mailContent instanceof InputStream ? (InputStream) mailContent : part.getInputStream(),
                    tempFile);
            content.getFiles()
                    .add(new FileItem(StringUtils.defaultIfEmpty(part.getFileName(), "unknown"), tempFile));
        } catch (IOException e) {
            FileUtils.deleteQuietly(tempFile);
            throw e;
        }
    }
    assert content.getBody() != null;
}

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

protected void getAttachmentParts(Part part, String defaultFilename, MimetypeRegistry mimeService,
        ExecutionContext context) throws MessagingException, IOException {
    String filename = getFilename(part, defaultFilename);
    List<Blob> blobs = (List<Blob>) context.get(ATTACHMENTS_KEY);

    if (part.isMimeType("multipart/alternative")) {
        bodyContent += getText(part);//from   w  ww .  j ava2  s.co  m
    } else {
        if (!part.isMimeType("multipart/*")) {
            String disp = part.getDisposition();
            // no disposition => mail body, which can be also blob (image for
            // instance)
            if (disp == null && // convert only text
                    part.getContentType().toLowerCase().startsWith("text/")) {
                bodyContent += decodeMailBody(part);
            } else {
                Blob blob;
                try (InputStream in = part.getInputStream()) {
                    blob = Blobs.createBlob(in);
                }
                String mime = DEFAULT_BINARY_MIMETYPE;
                try {
                    if (mimeService != null) {
                        ContentType contentType = new ContentType(part.getContentType());
                        mime = mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob,
                                contentType.getBaseType());
                    }
                } catch (MessagingException | MimetypeDetectionException e) {
                    log.error(e);
                }
                blob.setMimeType(mime);

                blob.setFilename(filename);

                blobs.add(blob);
            }
        }

        if (part.isMimeType("multipart/*")) {
            // This is a Multipart
            Multipart mp = (Multipart) part.getContent();

            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                getAttachmentParts(mp.getBodyPart(i), defaultFilename, mimeService, context);
            }
        } else if (part.isMimeType(MESSAGE_RFC822_MIMETYPE)) {
            // This is a Nested Message
            getAttachmentParts((Part) part.getContent(), defaultFilename, mimeService, context);
        }
    }

}

From source file:org.apache.camel.component.mail.MailBinding.java

protected void extractAttachmentsFromMultipart(Multipart mp, Map<String, DataHandler> map)
        throws javax.mail.MessagingException, IOException {

    for (int i = 0; i < mp.getCount(); i++) {
        Part part = mp.getBodyPart(i);
        LOG.trace("Part #" + i + ": " + part);

        if (part.isMimeType("multipart/*")) {
            LOG.trace("Part #" + i + ": is mimetype: multipart/*");
            extractAttachmentsFromMultipart((Multipart) part.getContent(), map);
        } else {//from w  w  w. ja  v  a2  s .c  om
            String disposition = part.getDisposition();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Part #" + i + ": Disposition: " + part.getDisposition());
                LOG.trace("Part #" + i + ": Description: " + part.getDescription());
                LOG.trace("Part #" + i + ": ContentType: " + part.getContentType());
                LOG.trace("Part #" + i + ": FileName: " + part.getFileName());
                LOG.trace("Part #" + i + ": Size: " + part.getSize());
                LOG.trace("Part #" + i + ": LineCount: " + part.getLineCount());
            }

            if (disposition != null && (disposition.equalsIgnoreCase(Part.ATTACHMENT)
                    || disposition.equalsIgnoreCase(Part.INLINE))) {
                // only add named attachments
                String fileName = part.getFileName();
                if (fileName != null) {
                    LOG.debug("Mail contains file attachment: " + fileName);
                    // Parts marked with a disposition of Part.ATTACHMENT are clearly attachments
                    CollectionHelper.appendValue(map, fileName, part.getDataHandler());
                }
            }
        }
    }
}