Example usage for javax.mail Multipart getCount

List of usage examples for javax.mail Multipart getCount

Introduction

In this page you can find the example usage for javax.mail Multipart getCount.

Prototype

public synchronized int getCount() throws MessagingException 

Source Link

Document

Return the number of enclosed BodyPart objects.

Usage

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

/**
 * Get text from message//from   w ww.ja v a 2s.c o  m
 */
private static String getText(Part p) throws MessagingException, IOException {
    if (p.isMimeType("text/*")) {
        Object obj = p.getContent();
        String str = NO_BODY;

        if (obj instanceof InputStream) {
            InputStream is = (InputStream) obj;
            StringWriter writer = new StringWriter();
            IOUtils.copy(is, writer, "UTF-8");
            str = writer.toString();
        } else {
            str = (String) obj;
        }

        if (p.isMimeType("text/html")) {
            return "H" + str;
        } else if (p.isMimeType("text/plain")) {
            return "T" + str;
        } else {
            // Otherwise let's set as text/plain
            return "T" + str;
        }
    } else if (p.isMimeType("multipart/alternative")) {
        // prefer html over plain text
        Multipart mp = (Multipart) p.getContent();
        String text = "T" + NO_BODY;
        // log.info("Mime Parts: {}", mp.getCount());

        for (int i = 0; i < mp.getCount(); i++) {
            Part bp = mp.getBodyPart(i);

            if (bp.isMimeType("text/plain")) {
                text = getText(bp);
            } else if (bp.isMimeType("text/html")) {
                text = getText(bp);
                break;
            } else {
                text = 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 "T" + NO_BODY;
}

From source file:org.springintegration.demo.service.EmailTransformer.java

public void handleMultipart(Multipart multipart, javax.mail.Message mailMessage, List<Message<?>> messages) {
    final int count;
    try {/*from w ww . j  a v a  2 s  .  c  o m*/
        count = multipart.getCount();
    } catch (MessagingException e) {
        throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e);
    }

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

        final BodyPart bp;

        try {
            bp = multipart.getBodyPart(i);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving body part.", e);
        }

        final String contentType;
        final String filename;
        final String disposition;
        final String subject;

        try {
            contentType = bp.getContentType();
            filename = bp.getFileName();
            disposition = bp.getDisposition();
            subject = mailMessage.getSubject();

        } catch (MessagingException e) {
            throw new IllegalStateException("Unable to retrieve body part meta data.", e);
        }

        if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            LOGGER.info("Handdling attachment '{}', type: '{}'", filename, contentType);
        }

        final Object content;

        try {
            content = bp.getContent();
        } catch (IOException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        }

        if (content instanceof String) {

            final Message<String> message = MessageBuilder.withPayload((String) content)
                    .setHeader(FileHeaders.FILENAME, subject + ".txt").build();

            messages.add(message);

        } else if (content instanceof InputStream) {

            InputStream inputStream = (InputStream) content;
            ByteArrayOutputStream bis = new ByteArrayOutputStream();

            try {
                IOUtils.copy(inputStream, bis);
            } catch (IOException e) {
                throw new IllegalStateException(
                        "Error while copying input stream to the ByteArrayOutputStream.", e);
            }

            Message<byte[]> message = MessageBuilder.withPayload((bis.toByteArray()))
                    .setHeader(FileHeaders.FILENAME, filename).build();

            messages.add(message);

        } else if (content instanceof javax.mail.Message) {
            handleMessage((javax.mail.Message) content, messages);
        } else if (content instanceof Multipart) {
            Multipart mp2 = (Multipart) content;
            handleMultipart(mp2, mailMessage, messages);
        } else {
            throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName());
        }
    }

}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

private void addEmailAttachmentsToJob(final DepositEmailConfiguration depositEmailConfiguration,
        final MimeMessage mimeMessage, final MultiFilesJob job)
        throws MessagingException, IOException, FileNotFoundException {

    final String jobConfigurationFileName = depositEmailConfiguration.getJobConfigurationFileName();
    if (StringUtils.isNotBlank(jobConfigurationFileName)) {
        final File jobConfigurationFile = getJobConfigurationFile(
                depositEmailConfiguration.getApplicationName(), jobConfigurationFileName);
        job.addFile(Constants.MULTIPLE_FILES_JOB_CONFIGURATION, new FileInputStream(jobConfigurationFile));
    }//from  w w  w  .  j a v a  2 s .c  om

    final Object content = mimeMessage.getContent();
    Validate.isTrue(content instanceof Multipart, "only multipart emails can be processed");

    final Multipart multipart = (Multipart) content;
    for (int i = 0, n = multipart.getCount(); i < n; i++) {
        final Part part = multipart.getBodyPart(i);

        final String disposition = part.getDisposition();

        if ((disposition != null)
                && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
            final String name = part.getFileName();
            final String contentType = StringUtils.substringBefore(part.getContentType(), ";");
            MultiFilesJob.addDataToJob(contentType, name, part.getInputStream(), job);
        }
    }
}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * Drag the content from the message into a String
 * /* w w  w  .j av a2  s  .c  o m*/
 * @param m
 * @return
 */
private String getContent(Message m) {
    try {
        Object content = m.getContent();
        if (content instanceof String) {
            return (String) content;
        } else if (content instanceof Multipart) {

            Multipart multipart = (Multipart) content;
            int partCount = multipart.getCount();
            StringBuffer result = new StringBuffer();

            for (int j = 0; j < partCount; j++) {

                BodyPart bodyPart = multipart.getBodyPart(j);
                String mimeType = bodyPart.getContentType();

                Object partContent = bodyPart.getContent();
                if (partContent instanceof String) {
                    result.append((String) partContent);
                } else if (partContent instanceof Multipart) {

                    Multipart innerMultiPartContent = (Multipart) partContent;
                    int innerPartCount = innerMultiPartContent.getCount();
                    result.append("*** It has " + innerPartCount + "further BodyParts in it ***");
                } else if (partContent instanceof InputStream) {
                    result.append(IOUtils.toString((InputStream) partContent));

                }
            } // End of for
            return result.toString();
        } else if (content instanceof InputStream)
            return IOUtils.toString((InputStream) content);

    } catch (Exception e) {
        return "ERROR reading mail content " + e.getMessage();
    }
    return "ERROR reading mail content - unknown format";
}

From source file:mitm.application.djigzo.ca.PFXMailBuilderTest.java

private byte[] getPFX(MimeMessage message) throws Exception {
    Multipart mp;

    mp = (Multipart) message.getContent();

    BodyPart pdfPart = null;//from  w w w.  j a va  2s.c om

    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (part.isMimeType("application/octet-stream")) {
            pdfPart = part;
        }
    }

    assertNotNull(pdfPart);

    Object content = pdfPart.getContent();

    assertTrue(content instanceof ByteArrayInputStream);

    return IOUtils.toByteArray((ByteArrayInputStream) content);
}

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

private void mapMultiPart(Multipart multiPart) throws MessagingException, IOException, DocumentException {

    for (int i = 0, n = multiPart.getCount(); i < n; i++) {
        BodyPart bodyPart = multiPart.getBodyPart(i);
        // showPart(bodyPart);
        handlePart(bodyPart);/*from www.j  a v a  2 s . c  om*/
    }
}

From source file:org.alfresco.module.org_alfresco_module_rm.action.impl.SplitEmailAction.java

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.action.Action,
 *      org.alfresco.service.cmr.repository.NodeRef)
 *//* ww w .jav a2 s .  c  o  m*/
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    // get node type
    getNodeService().getType(actionedUponNodeRef);

    if (logger.isDebugEnabled()) {
        logger.debug("split email:" + actionedUponNodeRef);
    }

    if (getRecordService().isRecord(actionedUponNodeRef)) {
        if (!getRecordService().isDeclared(actionedUponNodeRef)) {
            ChildAssociationRef parent = getNodeService().getPrimaryParent(actionedUponNodeRef);

            /**
             * Check whether the email message has already been split - do nothing if it has already been split
             */
            List<AssociationRef> refs = getNodeService().getTargetAssocs(actionedUponNodeRef,
                    ImapModel.ASSOC_IMAP_ATTACHMENT);
            if (refs.size() > 0) {
                if (logger.isDebugEnabled()) {
                    logger.debug("mail message has already been split - do nothing");
                }
                return;
            }

            /**
             * Get the content and if its a mime message then create atachments for each part
             */
            try {
                ContentReader reader = getContentService().getReader(actionedUponNodeRef,
                        ContentModel.PROP_CONTENT);
                InputStream is = reader.getContentInputStream();
                MimeMessage mimeMessage = new MimeMessage(null, is);
                Object content = mimeMessage.getContent();
                if (content instanceof Multipart) {
                    Multipart multipart = (Multipart) content;

                    for (int i = 0, n = multipart.getCount(); i < n; i++) {
                        Part part = multipart.getBodyPart(i);
                        if ("attachment".equalsIgnoreCase(part.getDisposition())) {
                            createAttachment(actionedUponNodeRef, parent.getParentRef(), part);
                        }
                    }
                }
            } catch (Exception e) {
                throw new AlfrescoRuntimeException(I18NUtil.getMessage(MSG_NO_READ_MIME_MESSAGE, e.toString()),
                        e);
            }
        } else {
            throw new AlfrescoRuntimeException(
                    I18NUtil.getMessage(MSG_EMAIL_DECLARED, actionedUponNodeRef.toString()));
        }
    } else {
        throw new AlfrescoRuntimeException(
                I18NUtil.getMessage(MSG_EMAIL_NOT_RECORD, actionedUponNodeRef.toString()));
    }
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

public void processMultipart(Multipart multipart, Message message) throws MessagingException, IOException {
    int partsNumber = multipart.getCount();
    for (int i = 0; i < partsNumber; i++) {
        Part part = multipart.getBodyPart(i);
        processMailPart(part, message);// ww w .  j a  v a 2 s .  c  o m
    }
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

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

    try {//from w w w  . j a  v  a 2 s .c  o  m
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

From source file:org.alfresco.repo.imap.AttachmentsExtractor.java

public void extractAttachments(NodeRef messageRef, MimeMessage originalMessage)
        throws IOException, MessagingException {
    NodeRef attachmentsFolderRef = null;
    String attachmentsFolderName = null;
    boolean createFolder = false;
    switch (attachmentsExtractorMode) {
    case SAME:/*from   w w  w. j a  va  2s  .co  m*/
        attachmentsFolderRef = nodeService.getPrimaryParent(messageRef).getParentRef();
        break;
    case COMMON:
        attachmentsFolderRef = this.attachmentsFolderRef;
        break;
    case SEPARATE:
    default:
        String messageName = (String) nodeService.getProperty(messageRef, ContentModel.PROP_NAME);
        attachmentsFolderName = messageName + "-attachments";
        createFolder = true;
        break;
    }
    if (!createFolder) {
        nodeService.createAssociation(messageRef, attachmentsFolderRef,
                ImapModel.ASSOC_IMAP_ATTACHMENTS_FOLDER);
    }

    Object content = originalMessage.getContent();
    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;

        for (int i = 0, n = multipart.getCount(); i < n; i++) {
            Part part = multipart.getBodyPart(i);
            if ("attachment".equalsIgnoreCase(part.getDisposition())) {
                if (createFolder) {
                    attachmentsFolderRef = createAttachmentFolder(messageRef, attachmentsFolderName);
                    createFolder = false;
                }
                createAttachment(messageRef, attachmentsFolderRef, part);
            }
        }
    }

}