Example usage for javax.mail Part getContent

List of usage examples for javax.mail Part getContent

Introduction

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

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

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

public void buildAttachments(List<Attach> attachs, Part part, String baseStorePath)
        throws MessagingException, IOException {
    if (part.isMimeType(MULTIPART_TYPE)) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            buildAttachments(attachs, mp.getBodyPart(i), baseStorePath);
        }/*from  w  w w .  j  a  v  a 2 s.c o  m*/
    } else if (isAttach(part)) {
        attachs.add(getAttach(part, baseStorePath));
    }
}

From source file:com.openkm.util.MailUtils.java

/**
 * Add attachments to an imported mail.// w  w w .j  a  v a 2  s .  co m
 */
public static void addAttachments(String token, com.openkm.bean.Mail mail, Part p, String userId)
        throws MessagingException, IOException, UnsupportedMimeTypeException, FileSizeExceededException,
        UserQuotaExceededException, VirusDetectedException, ItemExistsException, PathNotFoundException,
        AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException {
    if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();

        for (int i = 1; i < count; i++) {
            BodyPart bp = mp.getBodyPart(i);

            if (bp.getFileName() != null) {
                String name = MimeUtility.decodeText(bp.getFileName());
                String fileName = FileUtils.getFileName(name);
                String fileExtension = FileUtils.getFileExtension(name);
                String testName = name;

                // Test if already exists a document with the same name in the mail
                for (int j = 1; OKMRepository.getInstance().hasNode(token,
                        mail.getPath() + "/" + testName); j++) {
                    // log.info("Trying with: {}", testName);
                    testName = fileName + " (" + j + ")." + fileExtension;
                }

                Document attachment = new Document();
                String mimeType = MimeTypeConfig.mimeTypes.getContentType(bp.getFileName().toLowerCase());
                attachment.setMimeType(mimeType);
                attachment.setPath(mail.getPath() + "/" + testName);
                InputStream is = bp.getInputStream();

                if (Config.REPOSITORY_NATIVE) {
                    new DbDocumentModule().create(token, attachment, is, bp.getSize(), userId);
                } else {
                    new JcrDocumentModule().create(token, attachment, is, userId);
                }

                is.close();
            }
        }
    }
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private String handleAlternative(Object o, String content) throws Exception {

    Multipart multipart = (Multipart) o;
    for (int k = 0, n = multipart.getCount(); k < n; k++) {
        Part part = multipart.getBodyPart(k);
        MimeBodyPart mbp = (MimeBodyPart) part;

        if (mbp.isMimeType("text/html")) {
            log.debug("---------------> Handle html alternative. ");
            content += (String) part.getContent();
        }/*from w w  w.  j ava2s  . c  om*/

    }

    return content;
}

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

/**
 * Return the primary text content of the message.
 *///from  ww  w .  j  av  a  2  s  . c o  m
private String getText(Part p) throws MessagingException, IOException {
    if (p.isMimeType("text/*")) {
        return decodeMailBody(p);
    }

    if (p.isMimeType("multipart/alternative")) {
        // prefer html text over plain text
        Multipart mp = (Multipart) p.getContent();
        String text = null;
        for (int i = 0; i < mp.getCount(); i++) {
            Part bp = mp.getBodyPart(i);
            if (bp.isMimeType("text/plain")) {
                if (text == null) {
                    text = getText(bp);
                }
                continue;
            } else if (bp.isMimeType("text/html")) {
                String s = getText(bp);
                if (s != null) {
                    return s;
                }
            } else {
                return getText(bp);
            }
        }
        return text;
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            String s = getText(mp.getBodyPart(i));
            if (s != null) {
                return s;
            }
        }
    }

    return null;
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

private Part convertRFC822(Part attachment) {
    try {/*w  w  w. jav  a 2  s.  c  o  m*/
        Object o = attachment.getContent();

        if (o instanceof MimeMessage) {
            MimeMessage message = (MimeMessage) o;

            MessagePDFBuilder pdfBuilder = this.clone();

            ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

            pdfBuilder.buildPDF(message, null, pdfStream);

            MimePart pdfPart = new MimeBodyPart();

            pdfPart.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(pdfStream.toByteArray(), "application/pdf")));

            String filename = getFilename(attachment, "message.pdf");

            if (!filename.toLowerCase().endsWith(".pdf")) {
                filename = filename + ".pdf";
            }

            pdfPart.setFileName(filename);

            return pdfPart;
        }
    } catch (IOException e) {
        logger.error("Error trying to converting to RFC822.");
    } catch (MessagingException e) {
        logger.error("Error trying to converting to RFC822.");
    } catch (DocumentException e) {
        logger.error("Error trying to converting to RFC822.");
    }

    return attachment;
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private String handleMulitipart(Object o, String content, InboxEvent inboxentry) throws Exception {

    Multipart multipart = (Multipart) o;

    for (int k = 0, n = multipart.getCount(); k < n; k++) {

        Part part = multipart.getBodyPart(k);
        String disposition = part.getDisposition();
        MimeBodyPart mbp = (MimeBodyPart) part;

        if ((disposition != null) && (disposition.equals(Part.ATTACHMENT))) {
            log.debug("---------------> Saving File " + part.getFileName() + " " + part.getContent());
            saveAttachment(part, inboxentry);

        } else {/*from w w  w  . j av  a  2s .co m*/
            // Check if plain
            if (mbp.isMimeType("text/plain")) {
                log.debug("---------------> Handle plain. ");
                content += "<PRE style=\"font-size: 12px;\">" + (String) part.getContent() + "</PRE>";
                // Check if html
            } else if (mbp.isMimeType("text/html")) {
                log.debug("---------------> Handle plain. ");
                content += (String) part.getContent();
            } else {
                // Special non-attachment cases here of
                // image/gif, text/html, ...
                log.debug("---------------> Special non-attachment cases " + " " + part.getContentType());
                if (mbp.isMimeType("multipart/*")) {
                    Object ob = part.getContent();
                    content = this.handleMulitipart(ob, content, inboxentry) + "\n\n" + content;
                } else {
                    saveAttachment(part, inboxentry);
                }
            }
        }
    }

    return content;
}

From source file:com.glaf.mail.business.MailBean.java

/**
 * ??stringBuffer? ??MimeType??????/* w w w.j a va 2  s.  c  o  m*/
 * 
 * @param part
 * @throws MessagingException
 * @throws IOException
 */
public void parseMailContent(Part part) throws MessagingException, IOException {
    String contentType = part.getContentType();
    int nameindex = contentType.indexOf("name");
    boolean conname = false;
    if (nameindex != -1) {
        conname = true;
    }
    logger.debug("contentType:" + contentType);
    if (part.isMimeType("text/plain") && !conname) {
        mail.setContent((String) part.getContent());
    } else if (part.isMimeType("text/html") && !conname) {
        mail.setHtml((String) part.getContent());
    } else if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();
        int count = multipart.getCount();
        for (int i = 0; i < count; i++) {
            parseMailContent(multipart.getBodyPart(i));
        }
    } else if (part.isMimeType("message/rfc822")) {
        parseMailContent((Part) part.getContent());
    }
}

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 {/*from   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: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  . ja  v  a 2s.  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.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

public void removeAll(Part part, BodyPart notDelete) throws MessagingException, IOException {
    if (isAttach(part)) {
        if (part != notDelete) {
            BodyPart multi = (BodyPart) part;
            Multipart parent = multi.getParent();
            parent.removeBodyPart(multi);
        }//from  w w w . j  a v a2s. c o m
    } else if (part.isMimeType(MULTIPART_TYPE)) {
        Multipart mp = (Multipart) part.getContent();
        List<BodyPart> toRemove = new ArrayList<BodyPart>();
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart bodyPart = mp.getBodyPart(i);
            if (removePart(bodyPart, notDelete)) {
                toRemove.add(bodyPart);
            } else {
                removeAll(bodyPart, notDelete);
            }
        }
        for (BodyPart bp : toRemove)
            mp.removeBodyPart(bp);
    }
}