Example usage for javax.mail Part ATTACHMENT

List of usage examples for javax.mail Part ATTACHMENT

Introduction

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

Prototype

String ATTACHMENT

To view the source code for javax.mail Part ATTACHMENT.

Click Source Link

Document

This part should be presented as an attachment.

Usage

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

private void handlePart(String foldername, Part part, Pattern pattern) throws KettleException {
    try {//  w w w  .  j a v  a 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.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 w  w. j a v a 2s.  c  o  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:org.pentaho.di.job.entries.getpop.MailConnection.java

public int getAttachedFilesCount(Message message, Pattern pattern) throws KettleException {
    Object content = null;/*from  ww  w .j  a v  a2  s . co 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:com.zimbra.cs.mime.Mime.java

public static Set<MPartInfo> getBody(List<MPartInfo> parts, boolean preferHtml) {
    if (parts.isEmpty()) {
        return Collections.emptySet();
    }//w w  w. j  av  a 2  s.  c  o  m

    Set<MPartInfo> bodies = null;

    // if top-level has no children, then it is the body
    MPartInfo top = parts.get(0);
    if (!top.isMultipart()) {
        if (!top.getDisposition().equals(Part.ATTACHMENT)) {
            (bodies = new HashSet<MPartInfo>(1)).add(top);
        }
    } else {
        bodies = getBodySubparts(top, preferHtml);
    }

    if (bodies == null) {
        bodies = Collections.emptySet();
    }
    return bodies;
}

From source file:com.zimbra.cs.mime.Mime.java

private static Set<MPartInfo> getBodySubparts(MPartInfo base, boolean preferHtml) {
    // short-circuit malformed messages and message subparts
    if (!base.hasChildren() || base.isMessage())
        return null;

    String ctype = base.getContentType();
    List<MPartInfo> children;
    if (ctype.equals(MimeConstants.CT_MULTIPART_ALTERNATIVE)) {
        return getAlternativeBodySubpart(base.getChildren(), preferHtml);
    } else if (ctype.equals(MimeConstants.CT_MULTIPART_RELATED)) {
        return getRelatedBodySubpart(base.getChildren(), preferHtml, base.getContentTypeParameter("start"));
    } else if (ctype.equals(MimeConstants.CT_MULTIPART_REPORT)) {
        return getReportBodySubpart(base.getChildren(), preferHtml);
    } else if (ctype.equals(MimeConstants.CT_MULTIPART_MIXED) || !KNOWN_MULTIPART_TYPES.contains(ctype)) {
        children = base.getChildren();//from   w w w  .jav  a 2  s . c om
    } else {
        children = Arrays.asList(base.getChildren().get(0));
    }

    Set<MPartInfo> bodies = null;
    for (MPartInfo mpi : children) {
        if (mpi.isMultipart()) {
            Set<MPartInfo> found = getBodySubparts(mpi, preferHtml);
            if (found != null) {
                if (bodies == null)
                    bodies = new LinkedHashSet<MPartInfo>(found.size());
                bodies.addAll(found);
            }
        } else if (!mpi.getDisposition().equals(Part.ATTACHMENT) && !mpi.isMessage()
                && (mpi.getContentID() == null || mpi.getContentType().matches(MimeConstants.CT_TEXT_WILD))) {
            if (bodies == null)
                bodies = new LinkedHashSet<MPartInfo>(1);
            bodies.add(mpi);
        }
    }

    return bodies;
}

From source file:com.zimbra.cs.mime.Mime.java

private static Set<MPartInfo> getAlternativeBodySubpart(List<MPartInfo> children, boolean preferHtml) {
    // go through top-level children, stopping at first text part we are interested in
    MPartInfo alternative = null;//from   w  ww  .  j  a  v a 2 s  .  co m
    for (MPartInfo mpi : children) {
        boolean isAttachment = mpi.getDisposition().equals(Part.ATTACHMENT);
        // the Content-Type we want and the one we'd settle for...
        String wantType = preferHtml ? MimeConstants.CT_TEXT_HTML : MimeConstants.CT_TEXT_PLAIN;
        Set<String> altTypes = preferHtml ? HTML_ALTERNATES : TEXT_ALTERNATES;

        String ctype = mpi.getContentType();
        if (!isAttachment && ctype.equals(wantType)) {
            return setContaining(mpi);
        } else if (!isAttachment && altTypes.contains(ctype)) {
            if (alternative == null || !alternative.getContentType().equalsIgnoreCase(ctype)) {
                alternative = mpi;
            }
        } else if (mpi.isMultipart()) {
            Set<MPartInfo> body;
            if ((body = getBodySubparts(mpi, preferHtml)) != null)
                return body;
        }
    }

    if (alternative == null)
        return null;
    return setContaining(alternative);
}

From source file:com.zimbra.cs.mime.Mime.java

private static Set<MPartInfo> getReportBodySubpart(List<MPartInfo> children, boolean preferHtml) {
    //get all text subparts which match the preferHtml argument
    //if none match, return all alternative text subparts
    //in either case, text/rfc822-headers part is included in returned bodies if present
    Set<MPartInfo> subparts = new HashSet<MPartInfo>();
    Set<MPartInfo> alternatives = new HashSet<MPartInfo>();
    Set<MPartInfo> headers = new HashSet<MPartInfo>();
    for (MPartInfo mpi : children) {
        boolean isAttachment = mpi.getDisposition().equals(Part.ATTACHMENT);
        // the Content-Type we want and the one we'd settle for...
        String wantType = preferHtml ? MimeConstants.CT_TEXT_HTML : MimeConstants.CT_TEXT_PLAIN;
        Set<String> altTypes = preferHtml ? HTML_ALTERNATES : TEXT_ALTERNATES;

        String ctype = mpi.getContentType();
        if (!isAttachment && ctype.equals(wantType)) {
            subparts.add(mpi);//w  ww  .j a  v a 2  s  .  c o m
        } else if (!isAttachment && altTypes.contains(ctype)) {
            alternatives.add(mpi);
        } else if (!isAttachment && ctype.equals(MimeConstants.CT_TEXT_RFC822_HEADERS)) {
            headers.add(mpi);
        } else if (mpi.isMultipart()) {
            Set<MPartInfo> body;
            if ((body = getBodySubparts(mpi, preferHtml)) != null)
                subparts.addAll(body);
        }
    }
    if (subparts.size() == 0) {
        alternatives.addAll(headers);
        return (alternatives.size() == 0 ? null : alternatives);
    } else {
        subparts.addAll(headers);
        return subparts;
    }
}

From source file:com.sonicle.webtop.mail.Service.java

private boolean appendReplyParts(Part p, StringBuffer htmlsb, StringBuffer textsb, ArrayList<String> attnames)
        throws MessagingException, IOException {
    boolean isHtml = false;
    String disp = p.getDisposition();
    if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT) && !p.isMimeType("message/*")) {
        if (attnames != null) {/*from w w w .j  a  va  2s .  com*/
            String id[] = p.getHeader("Content-ID");
            if (id == null || id[0] == null) {
                String filename = p.getFileName();
                if (filename != null) {
                    if (filename.startsWith("<")) {
                        filename = filename.substring(1);
                    }
                    if (filename.endsWith(">")) {
                        filename = filename.substring(0, filename.length() - 1);
                    }
                }
                if (filename != null) {
                    attnames.add(filename);
                }
            }
        }
        return false;
    }
    if (p.isMimeType("text/html")) {
        //String htmlcontent=(String)p.getContent();
        String htmlcontent = getTextContentAsString(p);
        textsb.append(MailUtils.htmlToText(MailUtils.htmlunescapesource(htmlcontent)));
        htmlsb.append(MailUtils.htmlescapefixsource(/*getBodyInnerHtml(*/htmlcontent/*)*/));
        isHtml = true;
    } else if (p.isMimeType("text/plain")) {
        String content = getTextContentAsString(p);
        textsb.append(content);
        htmlsb.append(startpre + MailUtils.htmlescape(content) + endpre);
        isHtml = false;
    } else if (p.isMimeType("message/delivery-status") || p.isMimeType("message/disposition-notification")) {
        InputStream is = (InputStream) p.getContent();
        char cbuf[] = new char[8000];
        byte bbuf[] = new byte[8000];
        int n = 0;
        htmlsb.append(startpre);
        while ((n = is.read(bbuf)) >= 0) {
            if (n > 0) {
                for (int i = 0; i < n; ++i) {
                    cbuf[i] = (char) bbuf[i];
                }
                textsb.append(cbuf);
                htmlsb.append(MailUtils.htmlescape(new String(cbuf)));
            }
        }
        htmlsb.append(endpre);
        is.close();
        isHtml = false;
    } else if (p.isMimeType("multipart/alternative")) {
        Multipart mp = (Multipart) p.getContent();
        Part bestPart = null;
        for (int i = 0; i < mp.getCount(); ++i) {
            Part part = mp.getBodyPart(i);
            if (part.isMimeType("multipart/*")) {
                isHtml = appendReplyParts(part, htmlsb, textsb, attnames);
                if (isHtml) {
                    bestPart = null;
                    break;
                }
            } else if (part.isMimeType("text/html")) {
                bestPart = part;
                break;
            } else if (bestPart == null && part.isMimeType("text/plain")) {
                bestPart = part;
            } else if (bestPart == null && part.isMimeType("message/*")) {
                bestPart = part;
            }
        }
        if (bestPart != null) {
            isHtml = appendReplyParts(bestPart, htmlsb, textsb, attnames);
        }
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        for (int i = 0; i < mp.getCount(); ++i) {
            if (appendReplyParts(mp.getBodyPart(i), htmlsb, textsb, attnames)) {
                isHtml = true;
            }
        }
    } else if (p.isMimeType("message/*")) {
        Object content = p.getContent();
        if (appendReplyParts((MimeMessage) content, htmlsb, textsb, attnames)) {
            isHtml = true;
        }
    } else {
    }
    textsb.append('\n');
    textsb.append('\n');

    return isHtml;
}

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);/*from w  ww.  ja va 2s . co  m*/
            }
            mail.addAttachment(new NuclosFile(mimePart.getFileName(), out.toByteArray()));
        }
    }
}

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.
*//*from w w w.ja  v  a 2  s . c  om*/
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;
}