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.duroty.utils.mail.MessageUtilities.java

/**
 * A 'safe' version of JavaMail getFileName() which doesn't throw
 * exceptions. Encoded filenames are also decoded if necessary. Why
 * doesn't JAVA Mail do this?//  ww w .j  a  v a 2  s  .  com
 *
 * @param part The part to interogate
 *
 * @return File name of the part, or null if missing or invalid
 *
 * @see javax.mail.Part
 */
public static String getFileName(Part part) {
    if (part == null) {
        return null;
    }

    String xname = null;

    try {
        xname = part.getFileName();
    } catch (MessagingException xex) {
    }

    // decode the file name if necessary
    if ((xname != null) && xname.startsWith("=?")) {
        try {
            xname = MimeUtility.decodeWord(xname);
        } catch (Exception xex) {
        }
    }

    return xname;
}

From source file:org.klco.email2html.OutputWriter.java

/**
 * Writes the attachment contained in the body part to a file.
 * //from w  ww .j  ava 2  s .  c o m
 * @param containingMessage
 *            the message this body part is contained within
 * @param part
 *            the part containing the attachment
 * @return the file that was created/written to
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws MessagingException
 *             the messaging exception
 */
public boolean writeAttachment(EmailMessage containingMessage, Part part)
        throws IOException, MessagingException {
    log.trace("writeAttachment");

    File attachmentFolder;
    File attachmentFile;
    InputStream in = null;
    OutputStream out = null;
    try {

        attachmentFolder = new File(outputDir.getAbsolutePath() + File.separator + config.getImagesSubDir()
                + File.separator + FILE_DATE_FORMAT.format(containingMessage.getSentDate()));
        if (!attachmentFolder.exists()) {
            log.debug("Creating attachment folder");
            attachmentFolder.mkdirs();
        }

        attachmentFile = new File(attachmentFolder, part.getFileName());
        log.debug("Writing attachment file: {}", attachmentFile.getAbsolutePath());
        if (!attachmentFile.exists()) {
            attachmentFile.createNewFile();
        }

        in = new BufferedInputStream(part.getInputStream());
        out = new BufferedOutputStream(new FileOutputStream(attachmentFile));

        log.debug("Downloading attachment");
        CRC32 checksum = new CRC32();
        for (int b = in.read(); b != -1; b = in.read()) {
            checksum.update(b);
            out.write(b);
        }

        if (this.excludeDuplicates) {
            log.debug("Computing checksum");
            long value = checksum.getValue();
            if (this.attachmentChecksums.contains(value)) {
                log.info("Skipping duplicate attachment: {}", part.getFileName());
                attachmentFile.delete();
                return false;
            } else {
                attachmentChecksums.add(value);
            }
        }

        log.debug("Attachement saved");
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }

    if (part.getContentType().toLowerCase().startsWith("image")) {
        log.debug("Creating renditions");
        String contentType = part.getContentType().substring(0, part.getContentType().indexOf(";"));
        log.debug("Creating renditions of type: " + contentType);

        for (Rendition rendition : renditions) {
            File renditionFile = new File(attachmentFolder, rendition.getName() + "-" + part.getFileName());
            try {
                if (!renditionFile.exists()) {
                    renditionFile.createNewFile();
                }
                log.debug("Creating rendition file: {}", renditionFile.getAbsolutePath());
                createRendition(attachmentFile, renditionFile, rendition);
                log.debug("Rendition created");
            } catch (OutOfMemoryError oome) {
                Runtime rt = Runtime.getRuntime();
                rt.gc();
                log.warn("Ran out of memory creating rendition: " + rendition, oome);

                log.warn("Free Memory: {}", rt.freeMemory());
                log.warn("Max Memory: {}", rt.maxMemory());
                log.warn("Total Memory: {}", rt.totalMemory());

                String[] command = null;
                if (rendition.getFill()) {
                    command = new String[] { "convert", attachmentFile.getAbsolutePath(), "-resize",
                            (rendition.getHeight() * 2) + "x", "-resize",
                            "'x" + (rendition.getHeight() * 2) + "<'", "-resize", "50%", "-gravity", "center",
                            "-crop", rendition.getHeight() + "x" + rendition.getWidth() + "+0+0", "+repage",
                            renditionFile.getAbsolutePath() };
                } else {
                    command = new String[] { "convert", attachmentFile.getAbsolutePath(), "-resize",
                            rendition.getHeight() + "x" + rendition.getWidth(),
                            renditionFile.getAbsolutePath() };

                }
                log.debug("Trying to resize with ImageMagick: " + StringUtils.join(command, " "));

                rt.exec(command);
            } catch (Exception t) {
                log.warn("Exception creating rendition: " + rendition, t);
            }
        }
    }
    return true;
}

From source file:org.apache.hupa.server.handler.GetMessageDetailsHandler.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.  j  av a  2s. co  m*/
 * @param con the current processing Content
 * @param sbPlain the StringBuffer to fill with text
 * @param attachmentList ArrayList with attachments
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 * @throws IOException
 */
protected boolean handleParts(MimeMessage message, Object con, StringBuffer sbPlain,
        ArrayList<MessageAttachment> attachmentList)
        throws UnsupportedEncodingException, MessagingException, IOException {
    boolean isHTML = false;
    if (con instanceof String) {
        if (message.getContentType().toLowerCase().startsWith("text/html")) {
            isHTML = true;
        } else {
            isHTML = false;
        }
        sbPlain.append((String) con);

    } else if (con instanceof Multipart) {

        Multipart mp = (Multipart) con;
        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 MessageAttachment();
                            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:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * Aggregates the e-mail message by reading it and turning it either into a
 * page or a file upload./*from   www. j av  a 2  s  . c  o  m*/
 * 
 * @param message
 *          the e-mail message
 * @param site
 *          the site to publish to
 * @throws MessagingException
 *           if fetching the message data fails
 * @throws IOException
 *           if writing the contents to the output stream fails
 */
protected Page aggregate(Message message, Site site)
        throws IOException, MessagingException, IllegalArgumentException {

    ResourceURI uri = new PageURIImpl(site, UUID.randomUUID().toString());
    Page page = new PageImpl(uri);
    Language language = site.getDefaultLanguage();

    // Extract title and subject. Without these two, creating a page is not
    // feasible, therefore both messages throw an IllegalArgumentException if
    // the fields are not present.
    String title = getSubject(message);
    String author = getAuthor(message);

    // Collect default settings
    PageTemplate template = site.getDefaultTemplate();
    if (template == null)
        throw new IllegalStateException("Missing default template in site '" + site + "'");
    String stage = template.getStage();
    if (StringUtils.isBlank(stage))
        throw new IllegalStateException(
                "Missing stage definition in template '" + template.getIdentifier() + "'");

    // Standard fields
    page.setTitle(title, language);
    page.setTemplate(template.getIdentifier());
    page.setPublished(new UserImpl(site.getAdministrator()), message.getReceivedDate(), null);

    // TODO: Translate e-mail "from" into site user and throw if no such
    // user can be found
    page.setCreated(site.getAdministrator(), message.getSentDate());

    // Start looking at the message body
    String contentType = message.getContentType();
    if (StringUtils.isBlank(contentType))
        throw new IllegalArgumentException("Message content type is unspecified");

    // Text body
    if (contentType.startsWith("text/plain")) {
        // TODO: Evaluate charset
        String body = null;
        if (message.getContent() instanceof String)
            body = (String) message.getContent();
        else if (message.getContent() instanceof InputStream)
            body = IOUtils.toString((InputStream) message.getContent());
        else
            throw new IllegalArgumentException("Message body is of unknown type");
        return handleTextPlain(body, page, language);
    }

    // HTML body
    if (contentType.startsWith("text/html")) {
        // TODO: Evaluate charset
        return handleTextHtml((String) message.getContent(), page, null);
    }

    // Multipart body
    else if ("mime/multipart".equalsIgnoreCase(contentType)) {
        Multipart mp = (Multipart) message.getContent();
        for (int i = 0, n = mp.getCount(); i < n; i++) {
            Part part = mp.getBodyPart(i);
            String disposition = part.getDisposition();
            if (disposition == null) {
                MimeBodyPart mbp = (MimeBodyPart) part;
                if (mbp.isMimeType("text/plain")) {
                    return handleTextPlain((String) mbp.getContent(), page, null);
                } else {
                    // TODO: Implement special non-attachment cases here of
                    // image/gif, text/html, ...
                    throw new UnsupportedOperationException("Multipart message bodies of type '"
                            + mbp.getContentType() + "' are not yet supported");
                }
            } else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) {
                logger.info("Skipping message attachment " + part.getFileName());
                // saveFile(part.getFileName(), part.getInputStream());
            }
        }

        throw new IllegalArgumentException("Multipart message did not contain any recognizable content");
    }

    // ?
    else {
        throw new IllegalArgumentException("Message body is of unknown type '" + contentType + "'");
    }
}

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  ww  . j  a  v a  2 s.c  o m*/
            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());
                }
            }
        }
    }
}

From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java

public boolean addPartToDocument(Part part, Map<String, Object> row, boolean outerMost) throws Exception {
    if (outerMost && part instanceof Message) {
        if (!addEnvelopToDocument(part, row)) {
            return false;
        }//  w  w  w.  j  a v  a  2s .c o  m
        // store hash
        row.put(HASH, DigestUtils.md5Hex((String) row.get(FROM_CLEAN) + "" + (String) row.get(SUBJECT)));
    }

    String ct = part.getContentType();
    ContentType ctype = new ContentType(ct);
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        int count = mp.getCount();
        if (part.isMimeType("multipart/alternative")) {
            count = 1;
        }
        for (int i = 0; i < count; i++) {
            addPartToDocument(mp.getBodyPart(i), row, false);
        }
    } else if (part.isMimeType("message/rfc822")) {
        addPartToDocument((Part) part.getContent(), row, false);
    } else {
        String disp = part.getDisposition();
        @SuppressWarnings("resource") // Tika will close stream
        InputStream is = part.getInputStream();
        String fileName = part.getFileName();
        Metadata md = new Metadata();
        md.set(HttpHeaders.CONTENT_TYPE, ctype.getBaseType().toLowerCase(Locale.ROOT));
        md.set(TikaMetadataKeys.RESOURCE_NAME_KEY, fileName);
        String content = this.tika.parseToString(is, md);
        if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (row.get(ATTACHMENT) == null) {
                row.put(ATTACHMENT, new ArrayList<String>());
            }
            List<String> contents = (List<String>) row.get(ATTACHMENT);
            contents.add(content);
            row.put(ATTACHMENT, contents);
            if (row.get(ATTACHMENT_NAMES) == null) {
                row.put(ATTACHMENT_NAMES, new ArrayList<String>());
            }
            List<String> names = (List<String>) row.get(ATTACHMENT_NAMES);
            names.add(fileName);
            row.put(ATTACHMENT_NAMES, names);
        } else {
            if (row.get(CONTENT) == null) {
                row.put(CONTENT, new ArrayList<String>());
            }
            List<String> contents = (List<String>) row.get(CONTENT);
            contents.add(content);
            row.put(CONTENT, contents);
        }
    }
    return true;
}

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);
        }/* www  . j  a v a2  s.  com*/
    } 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.sakaiproject.james.SakaiMailet.java

/**
 * Breaks email messages into parts which can be saved as files (saves as attachments) or viewed as plain text (added to body of message).
 * /*ww w.j  a  va  2  s . c o  m*/
 * @param siteId
 *        Site associated with attachments, if any
 * @param p
 *        The message-part embedded in a message..
 * @param id
 *        The string containing the message's id.
 * @param bodyBuf
 *        The string-buffers in which the plain/text and/or html/text message body is being built.
 * @param bodyContentType
 *        The value of the Content-Type header for the mesage body.
 * @param attachments
 *        The ReferenceVector in which references to attachments are collected.
 * @param embedCount
 *        An Integer that counts embedded messages (outer message is zero).
 * @return Value of embedCount (updated if this call processed any embedded messages).
 */
protected Integer parseParts(String siteId, Part p, String id, StringBuilder bodyBuf[],
        StringBuilder bodyContentType, List attachments, Integer embedCount)
        throws MessagingException, IOException {
    // increment embedded message counter
    if (p instanceof Message) {
        embedCount = Integer.valueOf(embedCount.intValue() + 1);
    }

    String type = p.getContentType();

    // discard if content-type is unknown
    if (type == null || "".equals(type)) {
        M_log.warn(this + " message with unknown content-type discarded");
    }

    // add plain text to bodyBuf[0]
    else if (p.isMimeType("text/plain") && p.getFileName() == null) {
        Object o = null;
        // let them convert to text if possible
        // but if bad encaps get the stream and do it ourselves
        try {
            o = p.getContent();
        } catch (java.io.UnsupportedEncodingException ignore) {
            o = p.getInputStream();
        }

        String txt = null;
        String innerContentType = p.getContentType();

        if (o instanceof String) {
            txt = (String) p.getContent();
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        else if (o instanceof InputStream) {
            InputStream in = (InputStream) o;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[in.available()];
            for (int len = in.read(buf); len != -1; len = in.read(buf))
                out.write(buf, 0, len);
            String charset = (new ContentType(innerContentType)).getParameter("charset");
            // RFC 2045 says if no char set specified use US-ASCII.
            // If specified but illegal that's less clear. The common case is X-UNKNOWN.
            // my sense is that UTF-8 is most likely these days but the sample we got
            // was actually ISO 8859-1. Could also justify using US-ASCII. Duh...
            if (charset == null)
                charset = "us-ascii";
            try {
                txt = out.toString(MimeUtility.javaCharset(charset));
            } catch (java.io.UnsupportedEncodingException ignore) {
                txt = out.toString("UTF-8");
            }
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        // remove extra line breaks added by mac Mail, perhaps others
        // characterized by a space followed by a line break
        if (txt != null) {
            txt = txt.replaceAll(" \n", " ");
        }

        // make sure previous message parts ended with newline
        if (bodyBuf[0].length() > 0 && bodyBuf[0].charAt(bodyBuf[0].length() - 1) != '\n')
            bodyBuf[0].append("\n");

        bodyBuf[0].append(txt);
    }

    // add html text to bodyBuf[1]
    else if (p.isMimeType("text/html") && p.getFileName() == null) {
        Object o = null;
        // let them convert to text if possible
        // but if bad encaps get the stream and do it ourselves
        try {
            o = p.getContent();
        } catch (java.io.UnsupportedEncodingException ignore) {
            o = p.getInputStream();
        }
        String txt = null;
        String innerContentType = p.getContentType();

        if (o instanceof String) {
            txt = (String) p.getContent();
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        else if (o instanceof InputStream) {
            InputStream in = (InputStream) o;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[in.available()];
            for (int len = in.read(buf); len != -1; len = in.read(buf))
                out.write(buf, 0, len);
            String charset = (new ContentType(innerContentType)).getParameter("charset");
            if (charset == null)
                charset = "us-ascii";
            try {
                txt = out.toString(MimeUtility.javaCharset(charset));
            } catch (java.io.UnsupportedEncodingException ignore) {
                txt = out.toString("UTF-8");
            }
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        // remove bad image tags and naughty javascript
        if (txt != null) {
            txt = Web.cleanHtml(txt);
        }

        bodyBuf[1].append(txt);
    }

    // process subparts of multiparts
    else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            embedCount = parseParts(siteId, mp.getBodyPart(i), id, bodyBuf, bodyContentType, attachments,
                    embedCount);
        }
    }

    // Discard parts with mime-type application/applefile. If an e-mail message contains an attachment is sent from
    // a macintosh, you may get two parts, one for the data fork and one for the resource fork. The part that
    // corresponds to the resource fork confuses users, this has mime-type application/applefile. The best thing
    // is to discard it.
    else if (p.isMimeType("application/applefile")) {
        M_log.warn(this + " message with application/applefile discarded");
    }

    // discard enriched text version of the message.
    // Sakai only uses the plain/text or html/text version of the message.
    else if (p.isMimeType("text/enriched") && p.getFileName() == null) {
        M_log.warn(this + " message with text/enriched discarded");
    }

    // everything else gets treated as an attachment
    else {
        String name = p.getFileName();

        // look for filenames not parsed by getFileName() 
        if (name == null && type.indexOf(NAME_PREFIX) != -1) {
            name = type.substring(type.indexOf(NAME_PREFIX) + NAME_PREFIX.length());
        }
        // ContentType can't handle filenames with spaces or UTF8 characters
        if (name != null) {
            String decodedName = MimeUtility.decodeText(name); // first decode RFC 2047
            type = type.replace(name, URLEncoder.encode(decodedName, "UTF-8"));
            name = decodedName;
        }

        ContentType cType = new ContentType(type);
        String disposition = p.getDisposition();
        int approxSize = p.getSize();

        if (name == null) {
            name = "unknown";
            // if file's parent is multipart/alternative,
            // provide a better name for the file
            if (p instanceof BodyPart) {
                Multipart parent = ((BodyPart) p).getParent();
                if (parent != null) {
                    String pType = parent.getContentType();
                    ContentType pcType = new ContentType(pType);
                    if (pcType.getBaseType().equalsIgnoreCase("multipart/alternative")) {
                        name = "message" + embedCount;
                    }
                }
            }
            if (p.isMimeType("text/html")) {
                name += ".html";
            } else if (p.isMimeType("text/richtext")) {
                name += ".rtx";
            } else if (p.isMimeType("text/rtf")) {
                name += ".rtf";
            } else if (p.isMimeType("text/enriched")) {
                name += ".etf";
            } else if (p.isMimeType("text/plain")) {
                name += ".txt";
            } else if (p.isMimeType("text/xml")) {
                name += ".xml";
            } else if (p.isMimeType("message/rfc822")) {
                name += ".txt";
            }
        }

        // read the attachments bytes, and create it as an attachment in content hosting
        byte[] bodyBytes = readBody(approxSize, p.getInputStream());
        if ((bodyBytes != null) && (bodyBytes.length > 0)) {
            // can we ignore the attachment it it's just whitespace chars??
            Reference attachment = createAttachment(siteId, attachments, cType.getBaseType(), name, bodyBytes,
                    id);

            // add plain/text attachment reference (if plain/text message)
            if (attachment != null && bodyBuf[0].length() > 0)
                bodyBuf[0]
                        .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n");

            // add html/text attachment reference (if html/text message)
            if (attachment != null && bodyBuf[1].length() > 0)
                bodyBuf[1].append(
                        "<p>[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]</p>");

            // add plain/text attachment reference (if no plain/text and no html/text)
            if (attachment != null && bodyBuf[0].length() == 0 && bodyBuf[1].length() == 0)
                bodyBuf[0]
                        .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n");
        }
    }

    return embedCount;
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

public int getAttachedFilesCount(Message message, Pattern pattern) throws KettleException {
    Object content = null;//from   ww  w  .ja  va2s. c  o m
    int retval = 0;
    try {
        content = message.getContent();
        if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            for (int i = 0, n = multipart.getCount(); i < n; i++) {
                Part part = multipart.getBodyPart(i);
                String disposition = part.getDisposition();

                if ((disposition != null) && (disposition.equalsIgnoreCase(Part.ATTACHMENT)
                        || disposition.equalsIgnoreCase(Part.INLINE))) {
                    String MimeText = null;
                    try {
                        MimeText = MimeUtility.decodeText(part.getFileName());
                    } catch (Exception e) {
                        // Ignore errors
                    }
                    if (MimeText != null) {
                        String filename = MimeUtility.decodeText(part.getFileName());
                        if (isWildcardMatch(filename, pattern)) {
                            retval++;
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.CountingAttachedFiles",
                "" + this.message.getMessageNumber()), e);
    } finally {
        if (content != null) {
            content = null;
        }
    }
    return retval;
}

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

private void dumpPart(Part p, Element msg, Document doc) throws Exception {
    Element content = null;//from   w w  w  . jav  a 2s  .c o  m
    if (p.isMimeType("text/plain")) {
        content = doc.createElement("PlainMessage");
        Text body = doc.createTextNode((String) p.getContent());
        content.appendChild(body);
    } else if (p.isMimeType("text/html")) {
        content = doc.createElement("HTMLMessage");
        CDATASection body = doc.createCDATASection((String) p.getContent());
        content.appendChild(body);
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        content = doc.createElement("Multipart");
        for (int i = 0; i < count; i++) {
            dumpPart(mp.getBodyPart(i), content, doc);
        }
    } else if (p.isMimeType("message/rfc822")) {
        content = doc.createElement("NestedMessage");
        dumpPart((Part) p.getContent(), content, doc);
    } else {
        content = doc.createElement("EncodedContent");
        DataHandler dh = p.getDataHandler();
        OutputStream os = new ByteArrayOutputStream();
        Base64EncodingOutputStream b64os = new Base64EncodingOutputStream(os);
        dh.writeTo(b64os);
        b64os.flush();
        b64os.close();
        content.appendChild(doc.createTextNode(os.toString()));
    }
    msg.appendChild(content);
    String filename = p.getFileName();
    if (filename != null) {
        content.setAttribute("file-name", filename);
    }
    String ct = p.getContentType();
    if (ct != null) {
        content.setAttribute("content-type", ct);
    }
    String desc = p.getDescription();
    if (desc != null) {
        content.setAttribute("description", desc);
    }
}