Example usage for javax.mail Part getFileName

List of usage examples for javax.mail Part getFileName

Introduction

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

Prototype

public String getFileName() throws MessagingException;

Source Link

Document

Get the filename associated with this part, if possible.

Usage

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

/**
 * Processes part of a message//w  w w. j  av  a2  s.  c o m
 */
private static String handleSimplePart(Part part, List<EmailAttachment> attachments, boolean ignoreAttachments)
        throws MessagingException, IOException {
    // Check for content disposition and content type
    String disposition = part.getDisposition();
    String contentType = part.getContentType();
    LOGGER.debug("disposition=" + disposition);
    LOGGER.debug("Body type is: " + contentType);

    // tread if the part is a message
    boolean inlineMessage = part.isMimeType("message/rfc822");
    if (inlineMessage) {
        LOGGER.debug("Inner message:" + part.getFileName());
        Message subMessage = (Message) part.getContent();
        StringBuffer s = handlePart(subMessage, attachments, ignoreAttachments);
        System.out.println();
        return s.toString();
    }
    if (disposition == null) {
        if ("image/BMP".equals(contentType)) {
            // BMP image add as attachment
            if (ignoreAttachments == false) {
                try {
                    attachments.add(createEmailAttachment(part, "image.bmp"));
                } catch (Exception e) {
                    // just ignore
                }
            }
            return null;
        } else if (part.isMimeType("text/*")) {
            return getText(part);
        } else {
            if (ignoreAttachments == false) {
                handleAttachment(part, attachments);
            }
            return null;
        }
    }
    if (disposition.equalsIgnoreCase(Part.INLINE)) {
        return handleInline(part, attachments, ignoreAttachments);
    }
    if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
        if (ignoreAttachments == false) {
            handleAttachment(part, attachments);
        }
        return null;
    }
    LOGGER.debug("Unknown disposition:" + disposition + "Threat as attachment");
    if (ignoreAttachments == false) {
        handleAttachment(part, attachments);
    }
    return null;
}

From source file:org.silverpeas.core.mail.extractor.EMLExtractor.java

private String getFileName(Part part) throws MessagingException {
    String fileName = part.getFileName();
    if (!StringUtil.isDefined(fileName)) {
        try {/*from www  .  j a va  2 s .  c o  m*/
            ContentType type = new ContentType(part.getContentType());
            fileName = type.getParameter("name");
        } catch (ParseException e) {
            SilverLogger.getLogger(this).error(e);
        }
    }
    if (StringUtil.isDefined(fileName) && fileName.startsWith("=?") && fileName.endsWith("?=")) {
        try {
            fileName = MimeUtility.decodeText(part.getFileName());
        } catch (UnsupportedEncodingException e) {
            SilverLogger.getLogger(this).error(e);
        }
    }
    return fileName;
}

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.RFC822ToTextConverter.java

protected Blob extractTextFromMessage(Blob blob) {
    if (blob == null) {
        return null;
    }/*  w w w  .  j  a  va 2  s.  c  o m*/
    File f = null;
    OutputStream fo = null;
    try {
        MimeMessage msg = new MimeMessage((Session) null, blob.getStream());
        f = File.createTempFile("rfc822totext", ".txt");
        fo = new FileOutputStream(f);
        List<Part> parts = getAttachmentParts(msg);
        writeInfo(fo, msg.getSubject());
        writeInfo(fo, msg.getFrom());
        writeInfo(fo, msg.getRecipients(RecipientType.TO));
        writeInfo(fo, msg.getRecipients(RecipientType.CC));
        for (Part part : parts) {
            writeInfo(fo, part.getFileName());
            writeInfo(fo, part.getDescription());
            byte[] extracted = extractTextFromMessagePart(part);
            if (extracted != null) {
                writeInfo(fo, extracted);
            }
        }
        Blob outblob = new FileBlob(new FileInputStream(f));
        outblob.setMimeType(descriptor.getDestinationMimeType());
        return outblob;
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (fo != null) {
            try {
                fo.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
        if (f != null) {
            f.delete();
        }
    }
    return null;
}

From source file:org.alfresco.email.server.impl.subetha.SubethaEmailMessagePart.java

/**
 * Object can be built on existing message part only.
 * /*from   w  ww  . j a  v  a  2 s  .co  m*/
 * @param messagePart Message part.
 */
public SubethaEmailMessagePart(Part messagePart) {
    ParameterCheck.mandatory("messagePart", messagePart);

    try {
        fileSize = messagePart.getSize();
        fileName = messagePart.getFileName();
        contentType = messagePart.getContentType();

        Matcher matcher = encodingExtractor.matcher(contentType);
        if (matcher.find()) {
            encoding = matcher.group(1);
            if (!Charset.isSupported(encoding)) {
                throw new EmailMessageException(ERR_UNSUPPORTED_ENCODING, encoding);
            }
        }

        try {
            contentInputStream = messagePart.getInputStream();
        } catch (Exception ex) {
            throw new EmailMessageException(ERR_FAILED_TO_READ_CONTENT_STREAM, ex.getMessage());
        }
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_INCORRECT_MESSAGE_PART, e.getMessage());
    }
}

From source file:org.silverpeas.components.mailinglist.service.job.MailProcessor.java

protected String getFileName(Part part) throws MessagingException {
    String fileName = part.getFileName();
    if (fileName == null) {
        try {//from ww w.  ja  v  a 2  s  . c  om
            ContentType type = new ContentType(part.getContentType());
            fileName = type.getParameter("name");
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return fileName;
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

protected String getFileName(Part part) throws MessagingException {
    String fileName = part.getFileName();
    if (fileName == null) {
        try {/* w  w  w  .j ava  2  s. c  o  m*/
            ContentType type = new ContentType(part.getContentType());
            fileName = type.getParameter("name");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return fileName;
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Handle the parts of the given message. The method will call itself
 * recursively to handle all nested parts
 *
 * @param message the MimeMessage//from   w w w . ja va  2 s  .  c  om
 * @param content the current processing Content
 * @param sbPlain the StringBuffer to fill with text
 * @param attachmentList ArrayList with attachments
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 * @throws IOException
 */
public static boolean handleParts(Message message, Object content, StringBuffer sbPlain,
        ArrayList<MessageAttachment> attachmentList)
        throws UnsupportedEncodingException, MessagingException, IOException {
    boolean isHTML = false;
    if (content instanceof String) {
        if (message.getContentType().toLowerCase().startsWith("text/html")) {
            isHTML = true;
        } else {
            isHTML = false;
        }
        sbPlain.append((String) content);

    } else if (content instanceof Multipart) {

        Multipart mp = (Multipart) content;
        String multipartContentType = mp.getContentType().toLowerCase();

        String text = null;

        if (multipartContentType.startsWith("multipart/alternative")) {
            isHTML = handleMultiPartAlternative(mp, sbPlain);
        } else {
            for (int i = 0; i < mp.getCount(); i++) {
                Part part = mp.getBodyPart(i);

                String contentType = part.getContentType().toLowerCase();

                Boolean bodyRead = sbPlain.length() > 0;

                if (!bodyRead && contentType.startsWith("text/plain")) {
                    isHTML = false;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("text/html")) {
                    isHTML = true;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("message/rfc822")) {
                    // Extract the message and pass it
                    MimeMessage msg = (MimeMessage) part.getDataHandler().getContent();
                    isHTML = handleParts(msg, msg.getContent(), sbPlain, attachmentList);
                } else {
                    if (part.getFileName() != null) {
                        // Inline images are not added to the attachment
                        // list
                        // TODO: improve the in-line images detection
                        if (part.getHeader("Content-ID") == null) {
                            MessageAttachment attachment = new MessageAttachmentImpl();
                            attachment.setName(MimeUtility.decodeText(part.getFileName()));
                            attachment.setContentType(part.getContentType());
                            attachment.setSize(part.getSize());
                            attachmentList.add(attachment);
                        }
                    } else {
                        isHTML = handleParts(message, part.getContent(), sbPlain, attachmentList);
                    }
                }

            }
            if (text != null)
                sbPlain.append(text);
        }

    }
    return isHTML;
}

From source file:org.alfresco.module.org_alfresco_module_rm.action.impl.SplitEmailAction.java

/**
 * Create attachment from Mime Message Part
 * @param messageNodeRef - the node ref of the mime message
 * @param parentNodeRef - the node ref of the parent folder
 * @param part//from www . j av  a 2s  . c om
 * @throws MessagingException
 * @throws IOException
 */
private void createAttachment(NodeRef messageNodeRef, NodeRef parentNodeRef, Part part)
        throws MessagingException, IOException {
    String fileName = part.getFileName();
    try {
        fileName = MimeUtility.decodeText(fileName);
    } catch (UnsupportedEncodingException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("Cannot decode file name '" + fileName + "'", e);
        }
    }

    Map<QName, Serializable> messageProperties = getNodeService().getProperties(messageNodeRef);
    String messageTitle = (String) messageProperties.get(ContentModel.PROP_NAME);
    if (messageTitle == null) {
        messageTitle = fileName;
    } else {
        messageTitle = messageTitle + " - " + fileName;
    }

    ContentType contentType = new ContentType(part.getContentType());

    Map<QName, Serializable> docProps = new HashMap<QName, Serializable>(1);
    docProps.put(ContentModel.PROP_NAME, messageTitle + " - " + fileName);
    docProps.put(ContentModel.PROP_TITLE, fileName);

    /**
     * Create an attachment node in the same folder as the message
     */
    ChildAssociationRef attachmentRef = getNodeService().createNode(parentNodeRef, ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, fileName), ContentModel.TYPE_CONTENT,
            docProps);

    /**
     * Write the content into the new attachment node
     */
    ContentWriter writer = getContentService().getWriter(attachmentRef.getChildRef(), ContentModel.PROP_CONTENT,
            true);
    writer.setMimetype(contentType.getBaseType());
    OutputStream os = writer.getContentOutputStream();
    FileCopyUtils.copy(part.getInputStream(), os);

    /**
     * Create a link from the message to the attachment
     */
    createRMReference(messageNodeRef, attachmentRef.getChildRef());

}

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

public static String getFilename(Part Mess) throws MessagingException {
    // Part.getFileName() doesn't take into account any encoding that may have been 
    // applied to the filename so in order to obtain the correct filename we
    // need to retrieve it from the Content-Disposition

    String[] contentType = Mess.getHeader("Content-Disposition");
    if (contentType != null && contentType.length > 0) {
        int nameStartIndx = contentType[0].indexOf("filename=\"");
        if (nameStartIndx != -1) {
            String filename = contentType[0].substring(nameStartIndx + 10,
                    contentType[0].indexOf('\"', nameStartIndx + 10));
            try {
                filename = MimeUtility.decodeText(filename);
                return filename;
            } catch (UnsupportedEncodingException e) {
            }//from  ww w  .j  ava2s.c  om
        }
    }

    // couldn't determine it using the above, so fall back to more reliable but 
    // less correct option
    return Mess.getFileName();
}

From source file:de.contentreich.alfresco.repo.email.EMLTransformer.java

private void processPreviewMultiPart(Multipart multipart, Map<String, String> parts)
        throws MessagingException, IOException {
    logger.debug("Processing multipart of type {}", multipart.getContentType());
    // FIXME : Implement strict Depth or breadth first ?
    for (int i = 0, n = multipart.getCount(); i < n; i++) {
        Part part = multipart.getBodyPart(i);
        logger.debug("Processing part name {}, disposition = {}, type type = {}",
                new Object[] { part.getFileName(), part.getDisposition(), part.getContentType() });
        if (part.getContent() instanceof Multipart) {
            processPreviewMultiPart((Multipart) part.getContent(), parts);

        } else if (part.getContentType().contains("text")) {
            String key = part.getContentType().split(";")[0];
            String content = null;
            logger.debug("Add part with content type {} using key {}", part.getContentType(), key);

            if (key.endsWith("html")) {
                // <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
                // Breaks preview !
                content = part.getContent().toString().replaceAll("(?i)(?s)<meta.*charset=[^>]*>", "");
            } else {
                content = part.getContent().toString();
            }//w w  w.j  a v  a2s .  c om
            appendPreviewContent(parts, key, content);

        }

    }
}