Example usage for javax.mail BodyPart getFileName

List of usage examples for javax.mail BodyPart getFileName

Introduction

In this page you can find the example usage for javax.mail BodyPart getFileName.

Prototype

public String getFileName() throws MessagingException;

Source Link

Document

Get the filename associated with this part, if possible.

Usage

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *//*from  w  ww . java 2s . c  o  m*/
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

From source file:de.saly.elasticsearch.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withAttachments, final boolean stripTags, List<String> headersToFields)
        throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }/*from   www . ja v  a 2  s. c  o m*/

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments,
        final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }//from   ww  w  .  j  a  va2s .co m

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0, preferHtmlContent);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withHtmlContent) {

        // try {

        String htmlContent = getText(jmm, 0, true);

        im.setHtmlContent(htmlContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

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

/**
 * Add attachments to an imported mail.//from www.  j a  v  a  2s .  c  om
 */
public static void addAttachments(String token, com.ikon.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:ch.algotrader.util.mail.EmailTransformer.java

/**
 * Parses any {@link Multipart} instances that contains attachments
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 * @throws MessagingException//  w w  w .  j av  a  2 s .  c  om
 */
public void handleMultipart(Multipart multipart, List<EmailFragment> emailFragments) throws MessagingException {

    final int count = multipart.getCount();

    for (int i = 0; i < count; i++) {

        BodyPart bodyPart = multipart.getBodyPart(i);
        String filename = bodyPart.getFileName();
        String disposition = bodyPart.getDisposition();

        if (filename == null && bodyPart instanceof MimeBodyPart) {
            filename = ((MimeBodyPart) bodyPart).getContentID();
        }

        if (disposition == null) {

            //ignore message body

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

            try {
                try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        BufferedInputStream bis = new BufferedInputStream(bodyPart.getInputStream())) {

                    IOUtils.copy(bis, bos);

                    emailFragments.add(new EmailFragment(filename, bos.toByteArray()));

                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info(String.format("processing file: %s", new Object[] { filename }));
                    }

                }

            } catch (IOException e) {
                throw new MessagingException("error processing streams", e);
            }

        } else {
            throw new MessagingException("unkown disposition " + disposition);
        }
    }
}

From source file:org.nuxeo.client.api.marshaller.NuxeoResponseConverterFactory.java

@Override
public T convert(ResponseBody value) throws IOException {
    // Checking custom marshallers with the type of the method clientside.
    if (nuxeoMarshaller != null) {
        String response = value.string();
        logger.debug(response);/*  w  ww . j  ava  2 s . c  om*/
        JsonParser jsonParser = objectMapper.getFactory().createParser(response);
        return nuxeoMarshaller.read(jsonParser);
    }
    // Checking if multipart outputs.
    MediaType mediaType = MediaType.parse(value.contentType().toString());
    if (!(mediaType.type().equals(ConstantsV1.APPLICATION) && mediaType.subtype().equals(ConstantsV1.JSON))
            && !(mediaType.type().equals(ConstantsV1.APPLICATION)
                    && mediaType.subtype().equals(ConstantsV1.JSON_NXENTITY))) {
        if (mediaType.type().equals(ConstantsV1.MULTIPART)) {
            Blobs blobs = new Blobs();
            try {
                MimeMultipart mp = new MimeMultipart(
                        new ByteArrayDataSource(value.byteStream(), mediaType.toString()));
                int size = mp.getCount();
                for (int i = 0; i < size; i++) {
                    BodyPart part = mp.getBodyPart(i);
                    blobs.add(part.getFileName(), IOUtils.copyToTempFile(part.getInputStream()));
                }
            } catch (MessagingException reason) {
                throw new IOException(reason);
            }
            return (T) blobs;
        } else {
            return (T) new Blob(IOUtils.copyToTempFile(value.byteStream()));
        }
    }
    String nuxeoEntity = mediaType.nuxeoEntity();
    // Checking the type of the method clientside - aka object for Automation calls.
    if (javaType.getRawClass().equals(Object.class)) {
        if (nuxeoEntity != null) {
            switch (nuxeoEntity) {
            case ConstantsV1.ENTITY_TYPE_DOCUMENT:
                return (T) readJSON(value.charStream(), Document.class);
            case ConstantsV1.ENTITY_TYPE_DOCUMENTS:
                return (T) readJSON(value.charStream(), Documents.class);
            default:
                return (T) value;
            }
        } else {
            // This workaround is only for recordsets. There is not
            // header nuxeo-entity set for now serverside.
            String response = value.string();
            Object objectResponse = readJSON(response, Object.class);
            switch ((String) ((Map<String, Object>) objectResponse).get(ConstantsV1.ENTITY_TYPE)) {
            case ConstantsV1.ENTITY_TYPE_RECORDSET:
                return (T) readJSON(response, RecordSet.class);
            default:
                return (T) value;
            }
        }
    }
    Reader reader = value.charStream();
    try {
        return adapter.readValue(reader);
    } catch (IOException reason) {
        throw new NuxeoClientException(reason);
    } finally {
        closeQuietly(reader);
    }
}

From source file:ru.codemine.ccms.mail.EmailAttachmentExtractor.java

public void saveAllAttachment() {
    String protocol = ssl ? "imaps" : "imap";

    Properties props = new Properties();
    props.put("mail.store.protocol", protocol);

    try {/*from  w  w w . ja  v a 2  s .  c  om*/
        Session session = Session.getInstance(props);
        Store store = session.getStore();
        store.connect(host, port, username, password);

        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        for (Message msg : inbox.getMessages()) {
            if (!msg.isSet(Flags.Flag.SEEN)) {
                String fileNamePrefix = settingsService.getStorageEmailPath() + "msg-" + msg.getMessageNumber();
                Multipart multipart = (Multipart) msg.getContent();
                for (int i = 0; i < multipart.getCount(); i++) {
                    BodyPart bodyPart = multipart.getBodyPart(i);
                    if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && StringUtils.isNotEmpty(bodyPart.getFileName())) {
                        MimeBodyPart mimimi = (MimeBodyPart) bodyPart; // =(^.^)= 
                        mimimi.saveFile(fileNamePrefix + MimeUtility.decodeText(bodyPart.getFileName()));
                        msg.setFlag(Flags.Flag.SEEN, true);
                    }
                }
            }
        }
    } catch (IOException | MessagingException e) {
        log.error("? ? ?,  : "
                + e.getMessage());
    }

}

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

/**
 * Add attachments to an imported mail./*from   w  w w.  ja  v  a2s . c o  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:MultipartViewer.java

protected void setupDisplay(Multipart mp) {
    // we display the first body part in a main frame on the left, and then
    // on the right we display the rest of the parts as attachments

    GridBagConstraints gc = new GridBagConstraints();
    gc.gridheight = GridBagConstraints.REMAINDER;
    gc.fill = GridBagConstraints.BOTH;
    gc.weightx = 1.0;/*from   w  ww  .  ja v a 2s.  co  m*/
    gc.weighty = 1.0;

    // get the first part
    try {
        BodyPart bp = mp.getBodyPart(0);
        Component comp = getComponent(bp);
        add(comp, gc);

    } catch (MessagingException me) {
        add(new Label(me.toString()), gc);
    }

    // see if there are more than one parts
    try {
        int count = mp.getCount();

        // setup how to display them
        gc.gridwidth = GridBagConstraints.REMAINDER;
        gc.gridheight = 1;
        gc.fill = GridBagConstraints.NONE;
        gc.anchor = GridBagConstraints.NORTH;
        gc.weightx = 0.0;
        gc.weighty = 0.0;
        gc.insets = new Insets(4, 4, 4, 4);

        // for each one we create a button with the content type
        for (int i = 1; i < count; i++) { // we skip the first one 
            BodyPart curr = mp.getBodyPart(i);
            String label = null;
            if (label == null)
                label = curr.getFileName();
            if (label == null)
                label = curr.getDescription();
            if (label == null)
                label = curr.getContentType();

            Button but = new Button(label);
            but.addActionListener(new AttachmentViewer(curr));
            add(but, gc);
        }

    } catch (MessagingException me2) {
        me2.printStackTrace();
    }

}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

private static final String addSubIdentities(Element identification, BodyPart bp, InputStream inputStream,
        VitamArgument argument, ConfigLoader config) {
    Element newElt = XmlDom.factory.createElement(EMAIL_FIELDS.subidentity.name);
    String filename = null;/*from ww  w . jav a2  s. c o  m*/
    String result = "";
    try {
        filename = bp.getFileName();
        filename = StringUtils.toFileName(filename);
        if (filename != null) {
            Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.filename.name);
            elt.setText(filename);
            newElt.add(elt);
        } else {
            filename = "eml.eml";
        }
    } catch (MessagingException e) {
    }
    try {
        int size = bp.getSize();
        if (size > 0) {
            Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.attSize.name);
            elt.setText(Integer.toString(size));
            newElt.add(elt);
        }
    } catch (MessagingException e) {
    }
    try {
        String description = bp.getDescription();
        if (description != null) {
            Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.description.name);
            elt.setText(description);
            newElt.add(elt);
        }
    } catch (MessagingException e) {
    }
    try {
        String disposition = bp.getDisposition();
        if (disposition != null) {
            Element elt = XmlDom.factory.createElement(EMAIL_FIELDS.disposition.name);
            elt.setText(disposition);
            newElt.add(elt);
        }
    } catch (MessagingException e) {
    }
    File filetemp = null;
    FileOutputStream outputStream = null;
    try {
        // Force out to analysis
        if (config.extractFile) {
            filetemp = new File(argument.currentOutputDir, filename);
        } else {
            filetemp = File.createTempFile(StaticValues.PREFIX_TEMPFILE, filename);
        }
        byte[] buffer = new byte[8192];
        int read = 0;
        outputStream = new FileOutputStream(filetemp);
        while ((read = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, read);
        }
        outputStream.close();
        outputStream = null;
    } catch (IOException e1) {
        if (filetemp != null && !config.extractFile) {
            filetemp.delete();
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
            }
        }
        String status = "Error during access to attachment";
        newElt.addAttribute(EMAIL_FIELDS.status.name, status);
        identification.add(newElt);
        return "";
    }
    try {
        Commands.addFormatIdentification(newElt, filename, filetemp, config, argument);
        if (argument.extractKeyword) {
            // get back keyword in the main list
            Element keyw = (Element) newElt.selectSingleNode(EMAIL_FIELDS.keywords.name);
            if (keyw != null) {
                StringBuilder builder = new StringBuilder();
                @SuppressWarnings("unchecked")
                List<Element> elts = (List<Element>) keyw.selectNodes(EMAIL_FIELDS.keywordRank.name);
                for (Element elt : elts) {
                    String value = elt.attributeValue(EMAIL_FIELDS.keywordOccur.name);
                    int occur = Integer.parseInt(value) / 2 + 1;
                    @SuppressWarnings("unchecked")
                    List<Element> words = (List<Element>) elt.selectNodes(EMAIL_FIELDS.keywordWord.name);
                    for (Element eword : words) {
                        String word = eword.attributeValue(EMAIL_FIELDS.keywordValue.name) + " ";
                        for (int i = 0; i < occur; i++) {
                            builder.append(word);
                        }
                    }
                }
                result = builder.toString().trim();
            }
        }

    } catch (Exception e) {
        String status = "Error during identification";
        e.printStackTrace();
        config.addRankId(newElt);
        newElt.addAttribute(EMAIL_FIELDS.status.name, status);
    }
    if (filetemp != null && !config.extractFile) {
        filetemp.delete();
    }
    identification.add(newElt);
    return result;
}