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.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public List<GmailAttachment> getAttachements() {
    List<GmailAttachment> result = new ArrayList<GmailAttachment>();

    try {//w  ww  .ja va  2 s  .co  m
        Object content = this.source.getContent();
        if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            for (int i = 0; i < multipart.getCount(); i++) {
                Part bodyPart = multipart.getBodyPart(i);
                if (bodyPart.getDisposition() != null) {
                    if (bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                        result.add(new GmailAttachment(i, bodyPart.getFileName(), bodyPart.getContentType(),
                                bodyPart.getInputStream()));
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new GmailException("Failed to get attachements", e);
    }

    return result;
}

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public GmailAttachment getAttachment(int partIndex) {
    GmailAttachment result = null;/*from w  w  w .  j  a  v  a 2  s  . c  o  m*/

    try {
        Object content = this.source.getContent();
        if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            Part bodyPart = multipart.getBodyPart(partIndex);
            if (bodyPart.getDisposition() != null) {
                if (bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                    result = new GmailAttachment(partIndex, bodyPart.getFileName(), bodyPart.getContentType(),
                            bodyPart.getInputStream());
                }
            }
        } else {
            throw new GmailException("Failed to get attachement with partIndex :" + partIndex);
        }
    } catch (Exception e) {
        throw new GmailException("Failed to get attachement with partIndex :" + partIndex, e);
    }

    return result;
}

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 ww .  j a  v a2  s . c o 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.stimulus.archiva.domain.Email.java

protected boolean hasAttachment(Part p) throws MessagingException, IOException {

    if (p.getDisposition() != null && Compare.equalsIgnoreCase(p.getDisposition(), Part.ATTACHMENT)) {
        logger.debug("hasAttachment() attachment disposition.");
        return true;
    }/*from   ww w  .  j  a va2  s.c o m*/
    if (p.getFileName() != null) {
        logger.debug("hasAttachment() filename specified.");
        return true;
    }

    try {
        if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                logger.debug("hasAttachment() scanning multipart[" + i + "]");
                if (hasAttachment(mp.getBodyPart(i)))
                    return true;
            }
        } else if (p.isMimeType("message/rfc822")) {
            return hasAttachment((Part) p.getContent());
        }
    } catch (Exception e) {
        logger.debug("exception occurred while detecting attachment", e);
    }
    return false;
}

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

/**
 * Adds the attachment to the EmailMessage. Call this method when the email
 * content has most likely already been loaded.
 * //from w  w w.ja v a2  s . co m
 * @param containingMessage
 *            the Email Message to add the attachment to
 * @param part
 *            the content of the attachment
 * @throws IOException
 * @throws MessagingException
 */
public void addAttachment(EmailMessage containingMessage, Part part) throws IOException, MessagingException {
    log.trace("addAttachment");

    File attachmentFolder = new File(outputDir.getAbsolutePath() + File.separator + config.getImagesSubDir()
            + File.separator + FILE_DATE_FORMAT.format(containingMessage.getSentDate()));
    File attachmentFile = new File(attachmentFolder, part.getFileName());

    boolean addAttachment = true;
    boolean writeAttachment = false;
    if (!attachmentFolder.exists() || !attachmentFile.exists()) {
        log.warn("Attachment or folder missing, writing attachment {}", attachmentFile.getName());
        writeAttachment = true;
    }

    if (!writeAttachment && part.getContentType().toLowerCase().startsWith("image")) {
        for (Rendition rendition : renditions) {
            File renditionFile = new File(attachmentFolder, rendition.getName() + "-" + part.getFileName());
            if (!renditionFile.exists()) {
                log.warn("Rendition {} missing, writing attachment {}", renditionFile.getName(),
                        attachmentFile.getName());
                writeAttachment = true;
                break;
            }
        }
    }
    if (writeAttachment) {
        addAttachment = writeAttachment(containingMessage, part);
    } else {
        if (this.excludeDuplicates) {
            log.debug("Computing checksum");
            InputStream is = null;
            try {
                CRC32 checksum = new CRC32();
                is = new BufferedInputStream(new FileInputStream(attachmentFile));
                for (int read = is.read(); read != -1; read = is.read()) {
                    checksum.update(read);
                }
                long value = checksum.getValue();
                if (attachmentChecksums.contains(value)) {
                    addAttachment = false;
                } else {
                    attachmentChecksums.add(checksum.getValue());
                }
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    }
    if (addAttachment) {
        containingMessage.getAttachments().add(attachmentFile);
    } else {
        log.debug("Attachment is a duplicate, not adding as message attachment");
    }
}

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;//from  w ww  . j  a  v  a  2  s.  co 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:com.szmslab.quickjavamail.receive.MessageLoader.java

/**
 * ?????MessageContent????/*from   w ww  .ja v a  2s  .c om*/
 *
 * @param multiPart
 *            ?
 * @param msgContent
 *            ????
 * @throws MessagingException
 * @throws IOException
 */
private void setMultipartContent(Multipart multiPart, MessageContent msgContent)
        throws MessagingException, IOException {
    for (int i = 0; i < multiPart.getCount(); i++) {
        Part part = multiPart.getBodyPart(i);
        if (part.getContentType().indexOf("multipart") >= 0) {
            setMultipartContent((Multipart) part.getContent(), msgContent);
        } else {
            String disposition = part.getDisposition();
            if (Part.ATTACHMENT.equals(disposition)) {
                // Disposition?"attachment"???ContentType????
                msgContent.attachmentFileList.add(new AttachmentFile(MimeUtility.decodeText(part.getFileName()),
                        part.getDataHandler().getDataSource()));
            } else {
                if (part.isMimeType("text/html")) {
                    msgContent.html = part.getContent().toString();
                } else if (part.isMimeType("text/plain")) {
                    msgContent.text = part.getContent().toString();
                } else {
                    // Disposition?"inline"???ContentType??
                    if (Part.INLINE.equals(disposition)) {
                        String cid = "";
                        if (part instanceof MimeBodyPart) {
                            MimeBodyPart mimePart = (MimeBodyPart) part;
                            cid = mimePart.getContentID();
                        }
                        msgContent.inlineImageFileList
                                .add(new InlineImageFile(cid, MimeUtility.decodeText(part.getFileName()),
                                        part.getDataHandler().getDataSource()));
                    }
                }
            }
        }
    }
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Prepare extract multipart./*from w  ww. j a v a 2 s . c  om*/
 *
 * @param xhtml
 *            the xhtml
 * @param part
 *            the part
 * @param parentPart
 *            the parent part
 * @param context
 *            the context
 * @param attachmentList
 *            is list with attachments to fill
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
private void prepareExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart,
        ParseContext context, List<String> attachmentList)
        throws MessagingException, IOException, SAXException, TikaException {

    String disposition = part.getDisposition();
    if ((disposition != null && disposition.contains(Part.ATTACHMENT))) {
        String fileName = part.getFileName();
        if (fileName != null && fileName.startsWith("=?")) {
            fileName = MimeUtility.decodeText(fileName);
        }
        attachmentList.add(fileName);
    }

    String[] header = part.getHeader("Content-ID");
    String key = null;
    if (header != null) {
        for (String string : header) {
            key = string;
        }
    }

    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            prepareExtractMultipart(xhtml, mp.getBodyPart(i), part, context, attachmentList);
        }
    } else if (part.isMimeType(MimetypeMap.MIMETYPE_RFC822)) {
        prepareExtractMultipart(xhtml, (Part) part.getContent(), part, context, attachmentList);
    } else {

        if (key == null) {
            return;
        }
        // if ((disposition != null && disposition.contains(Part.INLINE))) {
        InputStream stream = part.getInputStream();

        File file = new File(workingDirectory, System.currentTimeMillis() + "");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.copy(stream, fileOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
        String src = file.getName();
        String replace = key.replace("<", "").replace(">", "");
        referencesCache.put(replace, src);
        // }

    }
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected void getParts(long userId, StringBundler bodyPlain, StringBundler bodyHtml, String contentPath,
        Part part, List<MailFile> mailFiles) throws IOException, MessagingException {

    String fileName = part.getFileName();
    Object content = part.getContent();

    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;

        for (int i = 0; i < multipart.getCount(); i++) {
            Part curPart = multipart.getBodyPart(i);

            getParts(userId, bodyPlain, bodyHtml,
                    contentPath.concat(StringPool.PERIOD).concat(String.valueOf(i)), curPart, mailFiles);
        }/*w w  w.  jav a  2 s.  c o  m*/
    } else if (Validator.isNull(fileName)) {
        String contentType = StringUtil.toLowerCase(part.getContentType());

        if (contentType.startsWith(ContentTypes.TEXT_PLAIN)) {
            bodyPlain.append(content.toString().replaceAll("\r\n", "<br />"));
        } else if (contentType.startsWith(ContentTypes.TEXT_HTML)) {
            bodyHtml.append(HtmlContentUtil.getInlineHtml(content.toString()));
        }
        //else if (contentType.startsWith(ContentTypes.MESSAGE_RFC822)) {
        //}
    } else {
        MailFile mailFile = new MailFile(contentPath.concat(StringPool.PERIOD).concat("-1"), fileName,
                part.getSize());

        mailFiles.add(mailFile);
    }
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * @param part//from w w w .  j av  a 2s  .  c o  m
 * @param attach
 * @return
 * @throws Exception
 */
private FileUtil handlePart(Part part, boolean attach) throws Exception {

    FileUtil file = null;

    String disposition = part.getDisposition();
    if (disposition == null) {
        // no nothing

    } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)) {

        file = new FileUtil();

        String fileName = part.getFileName();
        String contentType = part.getContentType();

        /* 
         * The contentType parameter contains mimetype and filename in one
         */
        String mimeType = contentType.split(";")[0].trim();

        file.setFilename(fileName);
        file.setMimetype(mimeType);

        InputStream inputStream = (attach == true) ? part.getInputStream() : null;
        if (inputStream != null)
            file.setInputStream(inputStream, mimeType);

    }

    return file;

}