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:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

public boolean hasAttach(Part part) throws MessagingException, IOException {
    if (part.isMimeType(MULTIPART_TYPE)) {
        Multipart mp = (Multipart) part.getContent();
        boolean has = false;
        for (int i = 0; i < mp.getCount(); i++) {
            if (hasAttach(mp.getBodyPart(i))) {
                has = true;//from w  ww.  j a  va  2  s . c  om
                break;
            }
        }
        return has;
    } else if (isAttach(part)) {
        return true;
    } else {
        return false;
    }
}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **//*from   www.  j a  v a  2 s.  c om*/

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}

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

/**
 * Prepare extract multipart./*  ww w.  j av a  2s  .  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: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   ww  w.jav  a 2s .  c om*/
    } 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);
    }
}

From source file:org.apache.axis2.transport.mail.SimpleMailListener.java

private void buildSOAPEnvelope(MimeMessage msg, MessageContext msgContext) throws AxisFault {
    //TODO we assume for the time being that there is only one attachement and this attachement contains  the soap evelope
    try {// w  w w . j  a v  a  2 s.  c o  m
        Multipart mp = (Multipart) msg.getContent();
        if (mp != null) {
            for (int i = 0, n = mp.getCount(); i < n; i++) {
                Part part = mp.getBodyPart(i);

                String disposition = part.getDisposition();

                if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
                    String soapAction;

                    /* Set the Charactorset Encoding */
                    String contentType = part.getContentType();
                    String charSetEncoding = BuilderUtil.getCharSetEncoding(contentType);
                    if (charSetEncoding != null) {
                        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                                charSetEncoding);
                    } else {
                        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                                MessageContext.DEFAULT_CHAR_SET_ENCODING);
                    }

                    /* SOAP Action */
                    soapAction = getMailHeaderFromPart(part,
                            org.apache.axis2.transport.mail.Constants.HEADER_SOAP_ACTION);
                    msgContext.setSoapAction(soapAction);

                    String contentDescription = getMailHeaderFromPart(part, "Content-Description");

                    /* As an input stream - using the getInputStream() method.
                    Any mail-specific encodings are decoded before this stream is returned.*/
                    if (contentDescription != null) {
                        msgContext.setTo(new EndpointReference(contentDescription));
                    }

                    if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
                        TransportUtils.processContentTypeForAction(contentType, msgContext);
                    } else {
                        // According to the mail sepec, mail transport should support only
                        // application/soap+xml;
                        String message = "According to the mail sepec, mail transport "
                                + "should support only application/soap+xml";
                        log.error(message);
                        throw new AxisFault(message);
                    }

                    String cte = getMailHeaderFromPart(part, "Content-Transfer-Encoding");
                    if (!(cte != null && cte.equalsIgnoreCase("base64"))) {
                        String message = "Processing of Content-Transfer-Encoding faild.";
                        log.error(message);
                        throw new AxisFault(message);
                    }
                    InputStream inputStream = part.getInputStream();
                    SOAPEnvelope envelope = TransportUtils.createSOAPMessage(msgContext, inputStream,
                            contentType);
                    msgContext.setEnvelope(envelope);
                }
            }

        }
    } catch (IOException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (XMLStreamException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

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

/**
 * Handle the parts of the given message. The method will call itself recursively to handle all nested parts
 * @param message the MimeMessage //from  w w  w  . j  a  v a  2 s.  c o  m
 * @param con the current processing Content
 * @param sbPlain the StringBuffer to fill with text
 * @param attachmentList ArrayList with attachments
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 * @throws IOException
 */
protected boolean handleParts(MimeMessage message, Object con, StringBuffer sbPlain,
        ArrayList<MessageAttachment> attachmentList)
        throws UnsupportedEncodingException, MessagingException, IOException {
    boolean isHTML = false;
    if (con instanceof String) {
        if (message.getContentType().toLowerCase().startsWith("text/html")) {
            isHTML = true;
        } else {
            isHTML = false;
        }
        sbPlain.append((String) con);

    } else if (con instanceof Multipart) {

        Multipart mp = (Multipart) con;
        String multipartContentType = mp.getContentType().toLowerCase();

        String text = null;

        if (multipartContentType.startsWith("multipart/alternative")) {
            isHTML = handleMultiPartAlternative(mp, sbPlain);
        } else {
            for (int i = 0; i < mp.getCount(); i++) {
                Part part = mp.getBodyPart(i);

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

                Boolean bodyRead = sbPlain.length() > 0;

                if (!bodyRead && contentType.startsWith("text/plain")) {
                    isHTML = false;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("text/html")) {
                    isHTML = true;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("message/rfc822")) {
                    // Extract the message and pass it
                    MimeMessage msg = (MimeMessage) part.getDataHandler().getContent();
                    isHTML = handleParts(msg, msg.getContent(), sbPlain, attachmentList);
                } else {
                    if (part.getFileName() != null) {
                        // Inline images are not added to the attachment list
                        // TODO: improve the in-line images detection 
                        if (part.getHeader("Content-ID") == null) {
                            MessageAttachment attachment = new MessageAttachment();
                            attachment.setName(MimeUtility.decodeText(part.getFileName()));
                            attachment.setContentType(part.getContentType());
                            attachment.setSize(part.getSize());
                            attachmentList.add(attachment);
                        }
                    } else {
                        isHTML = handleParts(message, part.getContent(), sbPlain, attachmentList);
                    }
                }

            }
            if (text != null)
                sbPlain.append(text);
        }

    }
    return isHTML;
}

From source file:com.studiostorti.ZimbraFlowHandler.java

private String getText(Part mimeMessage) throws MessagingException, IOException {
    if (mimeMessage != null) {
        if (mimeMessage.isMimeType("text/plain")) {
            return (String) mimeMessage.getContent();
        }//from  w ww .ja  v a 2  s . c om

        if (mimeMessage.isMimeType("multipart/alternative")) {
            Multipart multipart = (Multipart) mimeMessage.getContent();
            return getText(multipart.getBodyPart(0));
        } else if (mimeMessage.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) mimeMessage.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {
                String body = getText(multipart.getBodyPart(i));
                if (!body.equals(""))
                    return body;
            }
        }
    }

    return "";
}

From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

private String getBodyAsString(Object content) {
    Multipart mime = null;
    StringBuffer sb = new StringBuffer();
    if (content instanceof String) {
        return (String) content;
    } else if (content instanceof Multipart) {
        try {//from   w  w w .  j a  v  a 2 s.  c  om
            mime = (Multipart) content;
            for (int i = 0; i < mime.getCount(); ++i) {
                Part p = mime.getBodyPart(i);
                sb.append(p.getContent());
            }
        } catch (MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
    } else {
        Assert.assertTrue(false);
    }
    return sb.toString();
}

From source file:mitm.application.djigzo.relay.RelayHandler.java

private void extractMessageParts(MimeMessage message) throws MessagingException, IOException {
    /*//from   w w  w .j  a  v  a2 s  . c  o m
     * Fast fail. Only multipart mixed messages are supported. 
     */
    if (!message.isMimeType("multipart/mixed")) {
        return;
    }

    Multipart mp;

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

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

        if (part.isMimeType("message/rfc822")) {
            relayMessage = BodyPartUtils.extractFromRFC822(part);
        } else if (part.isMimeType("text/xml")) {
            metaPart = part;
        }

        if (metaPart != null && relayMessage != null) {
            break;
        }
    }
}

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

/**
 * @param mp//from  www.j av  a 2  s  .c o m
 * @return
 * @throws Exception
 */
private String messageFromMultipart(Multipart mp) throws Exception {

    String message = "";

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

        Part part = mp.getBodyPart(i);
        String text = messageFromPart(part);

        if (!text.equals(""))
            message = text;
    }

    return message;

}