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:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private void retrieveBody(cfSession _Session, Part Mess, cfQueryResultData popData, int Row, File attachmentDir)
        throws Exception {

    if (Mess.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) Mess.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            retrieveBody(_Session, mp.getBodyPart(i), popData, Row, attachmentDir);

    } else {//  w w  w  .  jav  a 2  s .c o m
        String filename = cfMailMessageData.getFilename(Mess);
        String dispos = Mess.getDisposition();

        // note: text/enriched shouldn't be treated as a text part of the email (see bug #2227)
        if ((dispos == null || dispos.equalsIgnoreCase(Part.INLINE)) && Mess.isMimeType("text/*")
                && !Mess.isMimeType("text/enriched")) {
            String content;
            String contentType = Mess.getContentType().toLowerCase();
            // support aliases of UTF-7 - UTF7, UNICODE-1-1-UTF-7, csUnicode11UTF7, UNICODE-2-0-UTF-7
            if (contentType.indexOf("utf-7") != -1 || contentType.indexOf("utf7") != -1) {
                content = new String(UTF7Converter.convert(readInputStream(Mess)));
            } else {
                try {
                    content = (String) Mess.getContent();
                } catch (UnsupportedEncodingException e) {
                    content = "Unable to retrieve message body due to UnsupportedEncodingException:"
                            + e.getMessage();
                } catch (ClassCastException e) {
                    // shouldn't happen but handle it gracefully
                    content = new String(readInputStream(Mess));
                }
            }

            if (Mess.isMimeType("text/html")) {
                popData.setCell(Row, 14, new cfStringData(content));
            } else if (Mess.isMimeType("text/plain")) {
                popData.setCell(Row, 15, new cfStringData(content));
            }
            popData.setCell(Row, 11, new cfStringData(content));

        } else if (attachmentDir != null) {

            File outFile;
            if (filename == null)
                filename = "unknownfile";

            outFile = getAttachedFilename(attachmentDir, filename,
                    getDynamic(_Session, "GENERATEUNIQUEFILENAMES").getBoolean());
            try {
                BufferedInputStream in = new BufferedInputStream(Mess.getInputStream());
                BufferedOutputStream out = new BufferedOutputStream(
                        cfEngine.thisPlatform.getFileIO().getFileOutputStream(outFile));
                IOUtils.copy(in, out);

                out.flush();
                out.close();
                in.close();

                //--[ Update the fields
                cfStringData cell = (cfStringData) popData.getCell(Row, 12);
                if (cell.getString().length() == 0)
                    cell = new cfStringData(filename);
                else
                    cell = new cfStringData(cell.getString() + "," + filename);

                popData.setCell(Row, 12, cell);

                cell = (cfStringData) popData.getCell(Row, 13);
                if (cell.getString().length() == 0)
                    cell = new cfStringData(outFile.toString());
                else
                    cell = new cfStringData(cell.getString() + "," + outFile.toString());

                popData.setCell(Row, 13, cell);

            } catch (Exception ignoreException) {
            }
        }
    }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Get a textual description of a part.//ww w .  j a  va 2 s .com
 *
 * @param part The part to interogate
 * @param buf a string buffer for the description
 * @param prefix a prefix for each line of the description
 * @param recurse boolean specifying wether to recurse through sub-parts or
 *        not
 *
 * @return StringBuffer containing the description of the part
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static StringBuffer getPartDescription(Part part, StringBuffer buf, String prefix, boolean recurse)
        throws MessagingException {
    if (buf == null) {
        return buf;
    }

    ContentType xctype = MessageUtilities.getContentType(part);

    String xvalue = xctype.toString();
    buf.append(prefix);
    buf.append("Content-Type: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDisposition();
    buf.append(prefix);
    buf.append("Content-Disposition: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDescription();
    buf.append(prefix);
    buf.append("Content-Description: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = MessageUtilities.getFileName(part);
    buf.append(prefix);
    buf.append("Content-Filename: ");
    buf.append(xvalue);
    buf.append('\n');

    if (part instanceof MimePart) {
        MimePart xmpart = (MimePart) part;
        xvalue = xmpart.getContentID();
        buf.append(prefix);
        buf.append("Content-ID: ");
        buf.append(xvalue);
        buf.append('\n');

        String[] langs = xmpart.getContentLanguage();

        if (langs != null) {
            buf.append(prefix);
            buf.append("Content-Language: ");

            for (int pi = 0; pi < langs.length; ++pi) {
                if (pi > 0) {
                    buf.append(", ");
                }

                buf.append(xvalue);
            }

            buf.append('\n');
        }

        xvalue = xmpart.getContentMD5();
        buf.append(prefix);
        buf.append("Content-MD5: ");
        buf.append(xvalue);
        buf.append('\n');

        xvalue = xmpart.getEncoding();
        buf.append(prefix);
        buf.append("Content-Encoding: ");
        buf.append(xvalue);
        buf.append('\n');
    }

    buf.append('\n');

    if (recurse && xctype.match("multipart/*")) {
        Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part);

        int xparts = xmulti.getCount();

        for (int xindex = 0; xindex < xparts; xindex++) {
            MessageUtilities.getPartDescription(xmulti.getBodyPart(xindex), buf, (prefix + "   "), true);
        }
    }

    return buf;
}

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

public int getAttachedFilesCount(Message message, Pattern pattern) throws KettleException {
    Object content = null;//from   w  ww .  ja v  a2 s. 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:org.pentaho.di.job.entries.getpop.MailConnection.java

private void handlePart(String foldername, Part part, Pattern pattern) throws KettleException {
    try {// ww  w  . j  a  va 2 s . c om
        String disposition = part.getDisposition();

        // The RFC2183 doesn't REQUIRE Content-Disposition header field so we'll create one to
        // fake out the code below.
        if (disposition == null || disposition.length() < 1) {
            disposition = Part.ATTACHMENT;
        }

        if (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)) {
                    // Save file
                    saveFile(foldername, filename, part.getInputStream());
                    updateSavedAttachedFilesCounter();
                    if (log.isDetailed()) {
                        log.logDetailed(BaseMessages.getString(PKG, "JobGetMailsFromPOP.AttachedFileSaved",
                                filename, "" + getMessage().getMessageNumber(), foldername));
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new KettleException(e);
    }
}

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;
        }//from  ww  w. jav a 2s  . c  om
        // 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.apache.manifoldcf.crawler.connectors.email.EmailConnector.java

/** Process a set of documents.
* This is the method that should cause each document to be fetched, processed, and the results either added
* to the queue of documents for the current job, and/or entered into the incremental ingestion manager.
* The document specification allows this class to filter what is done based on the job.
* The connector will be connected before this method can be called.
*@param documentIdentifiers is the set of document identifiers to process.
*@param statuses are the currently-stored document versions for each document in the set of document identifiers
* passed in above.//from   w ww  .  j av a2s.co m
*@param activities is the interface this method should use to queue up new document references
* and ingest documents.
*@param jobMode is an integer describing how the job is being run, whether continuous or once-only.
*@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one.
*/
@Override
public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec,
        IProcessActivity activities, int jobMode, boolean usesDefaultAuthority)
        throws ManifoldCFException, ServiceInterruption {

    List<String> requiredMetadata = new ArrayList<String>();
    for (int i = 0; i < spec.getChildCount(); i++) {
        SpecificationNode sn = spec.getChild(i);
        if (sn.getType().equals(EmailConfig.NODE_METADATA)) {
            String metadataAttribute = sn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME);
            requiredMetadata.add(metadataAttribute);
        }
    }

    // Keep a cached set of open folders
    Map<String, Folder> openFolders = new HashMap<String, Folder>();
    try {

        for (String documentIdentifier : documentIdentifiers) {
            String versionString = "_" + urlTemplate; // NOT empty; we need to make ManifoldCF understand that this is a document that never will change.

            // Check if we need to index
            if (!activities.checkDocumentNeedsReindexing(documentIdentifier, versionString))
                continue;

            String compositeID = documentIdentifier;
            String version = versionString;
            String folderName = extractFolderNameFromDocumentIdentifier(compositeID);
            String id = extractEmailIDFromDocumentIdentifier(compositeID);

            String errorCode = null;
            String errorDesc = null;
            Long fileLengthLong = null;
            long startTime = System.currentTimeMillis();
            try {
                try {
                    Folder folder = openFolders.get(folderName);
                    if (folder == null) {
                        getSession();
                        OpenFolderThread oft = new OpenFolderThread(session, folderName);
                        oft.start();
                        folder = oft.finishUp();
                        openFolders.put(folderName, folder);
                    }

                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug("Email: Processing document identifier '" + compositeID + "'");
                    SearchTerm messageIDTerm = new MessageIDTerm(id);

                    getSession();
                    SearchMessagesThread smt = new SearchMessagesThread(session, folder, messageIDTerm);
                    smt.start();
                    Message[] message = smt.finishUp();

                    String msgURL = makeDocumentURI(urlTemplate, folderName, id);

                    Message msg = null;
                    for (Message msg2 : message) {
                        msg = msg2;
                    }
                    if (msg == null) {
                        // email was not found
                        activities.deleteDocument(id);
                        continue;
                    }

                    if (!activities.checkURLIndexable(msgURL)) {
                        errorCode = activities.EXCLUDED_URL;
                        errorDesc = "Excluded because of URL ('" + msgURL + "')";
                        activities.noDocument(id, version);
                        continue;
                    }

                    long fileLength = msg.getSize();
                    if (!activities.checkLengthIndexable(fileLength)) {
                        errorCode = activities.EXCLUDED_LENGTH;
                        errorDesc = "Excluded because of length (" + fileLength + ")";
                        activities.noDocument(id, version);
                        continue;
                    }

                    Date sentDate = msg.getSentDate();
                    if (!activities.checkDateIndexable(sentDate)) {
                        errorCode = activities.EXCLUDED_DATE;
                        errorDesc = "Excluded because of date (" + sentDate + ")";
                        activities.noDocument(id, version);
                        continue;
                    }

                    String mimeType = "text/plain";
                    if (!activities.checkMimeTypeIndexable(mimeType)) {
                        errorCode = activities.EXCLUDED_DATE;
                        errorDesc = "Excluded because of mime type ('" + mimeType + "')";
                        activities.noDocument(id, version);
                        continue;
                    }

                    RepositoryDocument rd = new RepositoryDocument();
                    rd.setFileName(msg.getFileName());
                    rd.setMimeType(mimeType);
                    rd.setCreatedDate(sentDate);
                    rd.setModifiedDate(sentDate);

                    String subject = StringUtils.EMPTY;
                    for (String metadata : requiredMetadata) {
                        if (metadata.toLowerCase().equals(EmailConfig.EMAIL_TO)) {
                            Address[] to = msg.getRecipients(Message.RecipientType.TO);
                            String[] toStr = new String[to.length];
                            int j = 0;
                            for (Address address : to) {
                                toStr[j] = address.toString();
                            }
                            rd.addField(EmailConfig.EMAIL_TO, toStr);
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_FROM)) {
                            Address[] from = msg.getFrom();
                            String[] fromStr = new String[from.length];
                            int j = 0;
                            for (Address address : from) {
                                fromStr[j] = address.toString();
                            }
                            rd.addField(EmailConfig.EMAIL_TO, fromStr);

                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_SUBJECT)) {
                            subject = msg.getSubject();
                            rd.addField(EmailConfig.EMAIL_SUBJECT, subject);
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_BODY)) {
                            Multipart mp = (Multipart) msg.getContent();
                            for (int k = 0, n = mp.getCount(); k < n; k++) {
                                Part part = mp.getBodyPart(k);
                                String disposition = part.getDisposition();
                                if ((disposition == null)) {
                                    MimeBodyPart mbp = (MimeBodyPart) part;
                                    if (mbp.isMimeType(EmailConfig.MIMETYPE_TEXT_PLAIN)) {
                                        rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString());
                                    } else if (mbp.isMimeType(EmailConfig.MIMETYPE_HTML)) {
                                        rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); //handle html accordingly. Returns content with html tags
                                    }
                                }
                            }
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_DATE)) {
                            rd.addField(EmailConfig.EMAIL_DATE, sentDate.toString());
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_ENCODING)) {
                            Multipart mp = (Multipart) msg.getContent();
                            if (mp != null) {
                                String[] encoding = new String[mp.getCount()];
                                for (int k = 0, n = mp.getCount(); k < n; k++) {
                                    Part part = mp.getBodyPart(k);
                                    String disposition = part.getDisposition();
                                    if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)
                                            || (disposition.equals(Part.INLINE))))) {
                                        encoding[k] = part.getFileName().split("\\?")[1];

                                    }
                                }
                                rd.addField(EmailConfig.ENCODING_FIELD, encoding);
                            }
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_MIMETYPE)) {
                            Multipart mp = (Multipart) msg.getContent();
                            String[] MIMEType = new String[mp.getCount()];
                            for (int k = 0, n = mp.getCount(); k < n; k++) {
                                Part part = mp.getBodyPart(k);
                                String disposition = part.getDisposition();
                                if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)
                                        || (disposition.equals(Part.INLINE))))) {
                                    MIMEType[k] = part.getContentType();

                                }
                            }
                            rd.addField(EmailConfig.MIMETYPE_FIELD, MIMEType);
                        }
                    }

                    InputStream is = msg.getInputStream();
                    try {
                        rd.setBinary(is, fileLength);
                        activities.ingestDocumentWithException(id, version, msgURL, rd);
                        errorCode = "OK";
                        fileLengthLong = new Long(fileLength);
                    } finally {
                        is.close();
                    }
                } catch (InterruptedException e) {
                    throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED);
                } catch (MessagingException e) {
                    errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
                    errorDesc = e.getMessage();
                    handleMessagingException(e, "processing email");
                } catch (IOException e) {
                    errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
                    errorDesc = e.getMessage();
                    handleIOException(e, "processing email");
                    throw new ManifoldCFException(e.getMessage(), e);
                }
            } catch (ManifoldCFException e) {
                if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)
                    errorCode = null;
                throw e;
            } finally {
                if (errorCode != null)
                    activities.recordActivity(new Long(startTime), EmailConfig.ACTIVITY_FETCH, fileLengthLong,
                            documentIdentifier, errorCode, errorDesc, null);
            }
        }
    } finally {
        for (Folder f : openFolders.values()) {
            try {
                CloseFolderThread cft = new CloseFolderThread(session, f);
                cft.start();
                cft.finishUp();
            } catch (InterruptedException e) {
                throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED);
            } catch (MessagingException e) {
                handleMessagingException(e, "closing folders");
            }
        }
    }

}

From source file:MainClass.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/*  ww  w .  j  a va 2s  .  c  o  m*/

    /**
     * Dump input stream ..
     * 
     * InputStream is = p.getInputStream(); // If "is" is not already buffered,
     * wrap a BufferedInputStream // around it. if (!(is instanceof
     * BufferedInputStream)) is = new BufferedInputStream(is); int c; while ((c =
     * is.read()) != -1) System.out.write(c);
     * 
     */

    String ct = p.getContentType();
    try {
        pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
        pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
        pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids fetching the actual
     * content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
        pr("This is plain text");
        pr("---------------------------");
        if (!showStructure && !saveAttachments)
            System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        pr("This is a Multipart");
        pr("---------------------------");
        Multipart mp = (Multipart) p.getContent();
        level++;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
        level--;
    } else if (p.isMimeType("message/rfc822")) {
        pr("This is a Nested Message");
        pr("---------------------------");
        level++;
        dumpPart((Part) p.getContent());
        level--;
    } else {
        if (!showStructure && !saveAttachments) {
            /*
             * If we actually want to see the data, and it's not a MIME type we
             * know, fetch it and check its Java type.
             */
            Object o = p.getContent();
            if (o instanceof String) {
                pr("This is a string");
                pr("---------------------------");
                System.out.println((String) o);
            } else if (o instanceof InputStream) {
                pr("This is just an input stream");
                pr("---------------------------");
                InputStream is = (InputStream) o;
                int c;
                while ((c = is.read()) != -1)
                    System.out.write(c);
            } else {
                pr("This is an unknown type");
                pr("---------------------------");
                pr(o.toString());
            }
        } else {
            // just a separator
            pr("---------------------------");
        }
    }

    /*
     * If we're saving attachments, write out anything that looks like an
     * attachment into an appropriately named file. Don't overwrite existing
     * files to prevent mistakes.
     */
    if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // many mailers don't include a Content-Disposition
        if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (filename == null)
                filename = "Attachment" + attnum++;
            pr("Saving attachment to file " + filename);
            try {
                File f = new File(filename);
                if (f.exists())
                    // XXX - could try a series of names
                    throw new IOException("file exists");
                ((MimeBodyPart) p).saveFile(f);
            } catch (IOException ex) {
                pr("Failed to save attachment: " + ex);
            }
            pr("---------------------------");
        }
    }
}

From source file:msgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/*  w w  w  .ja  va  2  s .  c o  m*/

    /** Dump input stream .. 
            
    InputStream is = p.getInputStream();
    // If "is" is not already buffered, wrap a BufferedInputStream
    // around it.
    if (!(is instanceof BufferedInputStream))
        is = new BufferedInputStream(is);
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
            
    **/

    String ct = p.getContentType();
    try {
        pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
        pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
        pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids
     * fetching the actual content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
        pr("This is plain text");
        pr("---------------------------");
        if (!showStructure && !saveAttachments)
            System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        pr("This is a Multipart");
        pr("---------------------------");
        Multipart mp = (Multipart) p.getContent();
        level++;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
        level--;
    } else if (p.isMimeType("message/rfc822")) {
        pr("This is a Nested Message");
        pr("---------------------------");
        level++;
        dumpPart((Part) p.getContent());
        level--;
    } else {
        if (!showStructure && !saveAttachments) {
            /*
             * If we actually want to see the data, and it's not a
             * MIME type we know, fetch it and check its Java type.
             */
            Object o = p.getContent();
            if (o instanceof String) {
                pr("This is a string");
                pr("---------------------------");
                System.out.println((String) o);
            } else if (o instanceof InputStream) {
                pr("This is just an input stream");
                pr("---------------------------");
                InputStream is = (InputStream) o;
                int c;
                while ((c = is.read()) != -1)
                    System.out.write(c);
            } else {
                pr("This is an unknown type");
                pr("---------------------------");
                pr(o.toString());
            }
        } else {
            // just a separator
            pr("---------------------------");
        }
    }

    /*
     * If we're saving attachments, write out anything that
     * looks like an attachment into an appropriately named
     * file.  Don't overwrite existing files to prevent
     * mistakes.
     */
    if (saveAttachments && level != 0 && p instanceof MimeBodyPart && !p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // many mailers don't include a Content-Disposition
        if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (filename == null)
                filename = "Attachment" + attnum++;
            pr("Saving attachment to file " + filename);
            try {
                File f = new File(filename);
                if (f.exists())
                    // XXX - could try a series of names
                    throw new IOException("file exists");
                ((MimeBodyPart) p).saveFile(f);
            } catch (IOException ex) {
                pr("Failed to save attachment: " + ex);
            }
            pr("---------------------------");
        }
    }
}

From source file:com.flexoodb.common.FlexUtils.java

/**
* method to obtain a FileContainer containing the file wrapped in a mimemessage.
*
* @param  data the mimemessage in a byte array.
* @return a FileContainer containing the file.
*///ww w . j  av  a  2s . com
static public FileContainer extractFileFromMimeMessage(byte[] data) throws Exception {
    FileContainer fc = null;
    MimeMessage message = new MimeMessage(null, new ByteArrayInputStream(data));
    Object 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.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE)))) {
                if (part.getFileName() != null) {
                    fc = new FileContainer(part.getFileName(), part.getFileName(),
                            getBytesFromInputStream(part.getInputStream()));
                    break;
                }
            }
        }
    }
    return fc;
}

From source file:org.nuclos.server.ruleengine.RuleInterface.java

private void getAttachments(Multipart multipart, NuclosMail mail) throws MessagingException, IOException {
    for (int i = 0; i < multipart.getCount(); i++) {
        Part part = multipart.getBodyPart(i);
        String disposition = part.getDisposition();
        MimeBodyPart mimePart = (MimeBodyPart) part;
        logger.debug("Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType());

        if (part.getContent() instanceof Multipart) {
            logger.debug("Start child Multipart.");
            Multipart childmultipart = (Multipart) part.getContent();
            getAttachments(childmultipart, mail);
            logger.debug("Finished child Multipart.");
        } else if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            logger.debug("Attachment: " + mimePart.getFileName());
            InputStream in = mimePart.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[8192];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);//  w  w w .j a v  a2 s  .  c om
            }
            mail.addAttachment(new NuclosFile(mimePart.getFileName(), out.toByteArray()));
        }
    }
}