Example usage for javax.mail Part getContentType

List of usage examples for javax.mail Part getContentType

Introduction

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

Prototype

public String getContentType() throws MessagingException;

Source Link

Document

Returns the Content-Type of the content of this part.

Usage

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

private static String getText(Part part) throws MessagingException, IOException {
    String result = null;//from   w  w  w  . ja va 2 s.  c om
    if (part.isMimeType("text/plain")) {
        result = Text2HTML.addHTMLBreaks(StringEscapeUtils.escapeHtml((String) part.getContent()));

    } else if (part.isMimeType("text/html")) {
        result = part.getContent().toString();
    } else {
        LOGGER.debug("Process as text the part having mimeType:" + part.getContentType());
        result = Text2HTML.addHTMLBreaks(StringEscapeUtils.escapeHtml(part.getContent().toString()));
    }
    return result;
}

From source file:org.apache.hupa.server.servlet.DownloadAttachmentServlet.java

/**
 * Handle to write back the requested attachment
 *//*w  w  w.  j  a v  a2  s.co m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = (User) request.getSession().getAttribute(SConsts.USER_SESS_ATTR);
    if (user == null)
        throw new ServletException("Invalid session");

    String message_uuid = request.getParameter(SConsts.PARAM_UID);
    String attachmentName = request.getParameter(SConsts.PARAM_NAME);
    String folderName = request.getParameter(SConsts.PARAM_FOLDER);
    String mode = request.getParameter(SConsts.PARAM_MODE);
    boolean inline = "inline".equals(mode);
    if (!inline) {
        response.setHeader("Content-disposition", "attachment; filename=" + attachmentName + "");
    }
    InputStream in = null;
    OutputStream out = response.getOutputStream();

    IMAPFolder folder = null;
    try {
        Store store = cache.get(user);
        folder = (IMAPFolder) store.getFolder(folderName);
        if (folder.isOpen() == false) {
            folder.open(Folder.READ_ONLY);
        }
        Message m = folder.getMessageByUID(Long.parseLong(message_uuid));

        Object content = m.getContent();
        Part part = MessageUtils.handleMultiPart(logger, content, attachmentName);
        if (part.getContentType() != null) {
            response.setContentType(part.getContentType());
        } else {
            response.setContentType("application/download");
        }

        handleAttachmentData(request, m, attachmentName, part.getInputStream(), out);
        return;
    } catch (Exception e) {
        logger.error("Error while downloading attachment " + attachmentName + " of message " + message_uuid
                + " for user " + user.getName(), e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        if (folder != null) {
            try {
                folder.close(false);
            } catch (MessagingException e) {
            }
        }
    }
}

From source file:com.glaf.mail.MxMailHelper.java

public void processPart(Part p, Mail mail) throws Exception {
    String contentType = p.getContentType();
    InputStream inputStream = null;
    try {/*from   ww  w . j  a  v a  2  s.c o  m*/
        inputStream = new BufferedInputStream(p.getInputStream());
        if (contentType.startsWith("text/html")) {
            byte[] content = FileUtils.getBytes(inputStream);
            if (content != null && content.length > 0) {
                String html = new String(content);
                mail.setContent(html);
                mail.setMailType(TEXT_HTML);
            }
        } else if (contentType.startsWith("text/plain")) {
            byte[] content = FileUtils.getBytes(inputStream);
            if (content != null && content.length > 0) {
                mail.setContent(new String(content));
                mail.setMailType(TEXT_PLAIN);
            }
        } else if (contentType.startsWith("multipart") || contentType.startsWith("application/octet-stream")) {
            Multipart mp = (Multipart) p.getContent();
            processMultipart(mp, mail);
        }
    } catch (Exception ex) {
        throw ex;
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ex) {
        }
    }

}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

private static correoNoLeidos analizaParteDeMensaje2(correoNoLeidos correo, List<String> arc, List<String> rar,
        Part unaParte) {
    String r = null;/* w  ww. j  a  v a  2 s.  c  o m*/
    try {
        System.out.println("CORREO NUM: ");
        // Si es multipart, se analiza cada una de sus partes recursivamente.
        if (unaParte.isMimeType("multipart/*")) {
            Multipart multi;
            multi = (Multipart) unaParte.getContent();
            System.out.println("for MULTIPART");
            for (int j = 0; j < multi.getCount(); j++) {
                System.out.println("Si es multi");
                analizaParteDeMensaje2(correo, arc, rar, multi.getBodyPart(j));
            }
        } else {
            // Si es texto, se escribe el texto.
            if (unaParte.isMimeType("text/*")) {
                System.out.println("Texto " + unaParte.getContentType());
                System.out.println(unaParte.getContent());
                System.out.println("---------------------------------");
                correo.setContenido((String) unaParte.getContent());
            }

            // Si es imagen, se guarda en fichero y se visualiza en JFrame
            if (unaParte.isMimeType("image/*")) {
                System.out.println("IMAGEN SYSTEM");
                System.out.println("Imagen " + unaParte.getContentType());
                System.out.println("Fichero=" + unaParte.getFileName());
                System.out.println("---------------------------------");

                arc.add("/Intranet/resources/archivosMail/verCorreo/" + salvaImagenEnFichero(unaParte));
                //visualizaImagenEnJFrame(unaParte);
            } else {
                System.out.println("ELSE img");
                // Si no es ninguna de las anteriores, se escribe en pantalla
                // el tipo.
                System.out.println("Recibido " + unaParte.getContentType());
                System.out.println("---------------------------------");
                if (salvaImagenEnFichero(unaParte) != null & salvaImagenEnFichero(unaParte) != "") {
                    rar.add(salvaImagenEnFichero(unaParte));
                }
                correo.setContenido((String) unaParte.getContent());
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    correo.setImagenes(arc);
    correo.setRar(rar);
    return correo;
}

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

private void processSingleMessagePart(Part part) throws MessagingException, IOException {
    String partContentType = part.getContentType();
    String partFileName = getFileName(part);

    if (partFileName != null) {
        log.debug("Add named attachment: " + partFileName);
        setFile(partFileName, part.getInputStream());
        return;/*  ww  w .j a v a2  s.  c o m*/
    }

    if (!contentTypeIsReadableText(partContentType)) {
        log.debug("Add unnamed binary attachment.");
        setFile(null, part.getInputStream());
        return;
    }

    if (contentTypeIsPlainText(partContentType)) {
        log.debug("found plain text unnamed attachment [save for later processing]");
        messageBodyParts.get("text").add(part);
        return;
    }

    log.debug("found html unnamed attachment [save for later processing]");
    messageBodyParts.get("html").add(part);
}

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

/**
 * Interprets the body accordingly to the charset used. It relies on the content type being
 * ****;charset={charset};******// w w w. j  a  v a 2 s. c  o m
 *
 * @return the decoded String
 */
protected static String decodeMailBody(Part part) throws MessagingException, IOException {

    String encoding = null;

    // try to get encoding from header rather than from Stream !
    // unfortunately, this does not seem to be reliable ...
    /*
     * String[] cteHeader = part.getHeader("Content-Transfer-Encoding"); if (cteHeader!=null && cteHeader.length>0)
     * { encoding = cteHeader[0].toLowerCase(); }
     */

    // fall back to default sniffing
    // that will actually read the stream from server
    if (encoding == null) {
        encoding = MimeUtility.getEncoding(part.getDataHandler());
    }

    InputStream is = null;
    try {
        is = MimeUtility.decode(part.getInputStream(), encoding);
    } catch (IOException ex) {
        log.error("Unable to read content", ex);
        return "";
    }

    String contType = part.getContentType();
    final String charsetIdentifier = "charset=";
    final String ISO88591 = "iso-8859-1";
    final String WINDOWS1252 = "windows-1252";
    int offset = contType.indexOf(charsetIdentifier);
    String charset = "";
    if (offset >= 0) {
        charset = contType.substring(offset + charsetIdentifier.length());
        offset = charset.indexOf(";");
        if (offset > 0) {
            charset = charset.substring(0, offset);
        }
    }
    // Charset could be like "utf-8" or utf-8
    if (!"".equals(charset)) {
        charset = charset.replaceAll("\"", "");
    }
    log.debug("Content type: " + contType + "; charset: " + charset);
    if (charset.equalsIgnoreCase(ISO88591)) {
        // see
        // http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#character1
        // for more details see http://en.wikipedia.org/wiki/ISO_8859-1
        // section "ISO-8859-1 and Windows-1252 confusion"
        charset = WINDOWS1252;
        log.debug("Using replacing charset: " + charset);
    }
    String ret;
    byte[] streamContent = FileUtils.readBytes(is);
    if ("".equals(charset)) {
        ret = new String(streamContent);
    } else {
        try {
            ret = new String(streamContent, charset);
        } catch (UnsupportedEncodingException e) {
            // try without encoding
            ret = new String(streamContent);
        }
    }
    return ret;
}

From source file:org.apache.hupa.server.handler.GetMessageDetailsHandler.java

private boolean handleMultiPartAlternative(Multipart mp, StringBuffer sbPlain)
        throws MessagingException, IOException {
    String text = null;/*from  w ww .  j a  va  2  s .c  om*/
    boolean isHTML = false;
    for (int i = 0; i < mp.getCount(); i++) {
        Part part = mp.getBodyPart(i);

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

        // we prefer html
        if (text == null && contentType.startsWith("text/plain")) {
            isHTML = false;
            text = (String) part.getContent();
        } else if (contentType.startsWith("text/html")) {
            isHTML = true;
            text = (String) part.getContent();
        }
    }
    sbPlain.append(text);
    return isHTML;
}

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

private void addPartsToTextMessage(List<Part> someMessageParts) throws MessagingException, IOException {
    for (Part part : someMessageParts) {
        addToTextMessage(part.getContent().toString(), contentTypeIsPlainText(part.getContentType()));
    }/*w  w  w .j  av a  2  s . c om*/
}

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

/**
 * Object can be built on existing message part only.
 * //  www.j  av a2s.c  o  m
 * @param messagePart Message part.
 */
public SubethaEmailMessagePart(Part messagePart) {
    ParameterCheck.mandatory("messagePart", messagePart);

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

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

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

From source file:org.xmlactions.email.EMailParser.java

private void addPart(Part part) throws IOException, MessagingException, DocumentException {

    String contentType = part.getContentType();
    boolean isAttachment;

    if (part.getFileName() != null) {
        isAttachment = true;/*  w  ww  .j  a va 2s.  c  o m*/
    } else {
        isAttachment = false;
    }

    log.debug("isAttachment:" + isAttachment + " contentType:" + contentType);

    if (isAttachment == true) {
    } else {
        // Check if plain
        if (contentType.toLowerCase().indexOf("text/plain") >= 0) {
            log.debug("process text/plain");
            setIgnoreHTML(true); // if we get any text/plain for body
        } else if (isIgnoreHTML() == false && contentType.toLowerCase().indexOf("text/html") >= 0) {
            // log.debug("skipping text/html");
            log.debug("process text/html");
            InputStream is = convertHTMLToText(part.getInputStream());
            try {
            } finally {
                IOUtils.closeQuietly(is);
            }

        } else {
            log.debug("ignoring part [" + contentType + "]");
        }
    }
}