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:gov.nih.nci.cacis.nav.DefaultNotificationValidator.java

private void validateMultiparts(Multipart multipart) throws NotificationValidationException {
    try {//from  w ww .jav a2 s.c om
        if (multipart.getCount() != 2) {
            throw new NotificationValidationException(ERR_RQR_2_PRTS_MSG);
        }
        validateTextBodyPart(multipart.getBodyPart(0));
        validateAttachmentBodyPart(multipart.getBodyPart(1));
    } catch (MessagingException e) {
        throw new NotificationValidationException(ERR_INVALID_MULTIPART_MSG, e);
    }
}

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

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

    log.debug("\n\n\nhandlePart ==>>");
    log.debug("part.toString():" + part.toString());
    log.debug(//from www  .  ja  v  a2s  .com
            "part.getContent():" + (part.getFileName() == null ? part.getContent().toString() : "Attachment"));
    log.debug("part.getContentType():" + part.getContentType());
    log.debug("part.getFilename():" + part.getFileName());
    log.debug("part.isAttachment:" + part.getFileName());
    log.debug("part.isMessage:" + (part.getContent() instanceof Message));
    Object obj = part.getContent();
    if (obj instanceof Multipart) {
        Multipart mmp = (Multipart) obj;
        for (int i = 0; i < mmp.getCount(); i++) {
            Part bodyPart = mmp.getBodyPart(i);
            if (bodyPart instanceof Message) {
                setFirstMessageProcessed(true);// need to mark this when we
                // get a forwarded message
                // so we don't look for case
                // numbers in forwarded
                // emails.
            }
            handlePart(bodyPart);
        }
    } else if (obj instanceof Part) {
        if (obj instanceof Message) {
            setFirstMessageProcessed(true);// need to mark this when we get
            // a forwarded message so we
            // don't look for case numbers
            // in forwarded emails.
        }
        handlePart((Part) obj);
    } else {
        if (part instanceof MimeBodyPart) {
            MimeBodyPart p = (MimeBodyPart) part;
            Enumeration enumeration = p.getAllHeaders();
            while (enumeration.hasMoreElements()) {
                Object e = enumeration.nextElement();
                if (e == null)
                    e = null;
            }
            Object content = p.getContent();
            enumeration = p.getAllHeaderLines();
            while (enumeration.hasMoreElements()) {
                Object e = enumeration.nextElement();
                if (e == null)
                    e = null;
            }
            DataHandler dh = p.getDataHandler();
            if (dh == null)
                dh = null;
        }
        addPart(part);
        log.debug("=== Add Part ===");
        log.debug((String) (part.getFileName() != null ? "isAttachment" : part.getContent()));
        // log.info("not recognised class:" + obj.getClass().getName() +
        // "\n" + obj);
    }
    log.debug("<<== handlePart");
}

From source file:server.MailPop3Expert.java

@Override
public void run() {
    //obtengo la agenda
    List<String> agenda = XmlParcerExpert.getInstance().getAgenda();

    while (store.isConnected()) {
        try {/*w  ww . j  ava 2  s  .co  m*/

            // Abre la carpeta INBOX
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);

            // Obtiene los mails
            Message[] arrayMessages = folderInbox.getMessages();

            //procesa los mails
            for (int i = 0; i < arrayMessages.length; i++) {
                Message message = arrayMessages[i];
                Address[] fromAddress = message.getFrom();
                String from = fromAddress[0].toString();
                String subject = message.getSubject();
                String sentDate = message.getSentDate().toString();
                String messageContent = "";
                String contentType = message.getContentType();

                if (contentType.contains("multipart")) {
                    // Si el contenido es mulpart
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // si contiene un archivo
                        } else {
                            // el contenido del mensaje
                            messageContent = part.getContent().toString();
                        }
                    }

                } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }

                //parseo del from
                if (from.contains("<")) {
                    from = from.substring(from.indexOf("<") + 1, from.length() - 1);
                }

                //si esta en la agenda
                if (agenda.contains(from)) {
                    //obtiene la trama
                    try {
                        messageContent = messageContent.substring(messageContent.indexOf("&gt"),
                                messageContent.indexOf("&lt;") + 4);
                        if (messageContent.startsWith("&gt") && messageContent.endsWith("&lt;")) {
                            //procesa el mail
                            XmlParcerExpert.getInstance().processAndSaveMail(from, messageContent);
                            frame.loadMails();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //no lo guarda
                }

            }

            folderInbox.close(false);

            //duerme el hilo por el tiempo de la frecuencia
            Thread.sleep(frecuency * 60 * 1000);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * returns message parts//from w w  w .  j av  a 2  s .co m
 * @param content   
 * @return         message parts
 * @throws IOException
 * @throws MessagingException
 */
private List<BodyPart> getMessageParts(Multipart content) throws IOException, MessagingException {
    List<BodyPart> partList = new ArrayList<>();

    for (int partId = 0; partId < content.getCount(); partId++) {
        BodyPart part = content.getBodyPart(partId);

        if (part.getContentType().toLowerCase().contains("multipart/")) {

            partList.addAll(getMessageParts((Multipart) part.getContent()));
        } else {
            partList.add(part);
        }
    }

    return partList;
}

From source file:org.sourceforge.net.javamail4ews.transport.EwsTransport.java

private MessageBody createBodyFromPart(EmailMessage msg, Part part, boolean treatAsAttachement)
        throws MessagingException, IOException, ServiceLocalException {

    MessageBody mb = new MessageBody();
    if (part.isMimeType(TEXT_PLAIN)) {
        String s = (String) part.getContent();
        mb.setBodyType(BodyType.Text);
        mb.setText(s);//from www . j a  v a2s  . c  o  m
    } else if (part.isMimeType(TEXT_STAR)) {
        logger.debug("mime-type is '" + part.getContentType() + "' handling as " + TEXT_HTML);
        String s = (String) part.getContent();
        mb.setBodyType(BodyType.HTML);
        mb.setText(s);
    } else if (part.isMimeType(MULTIPART_ALTERNATIVE) && !treatAsAttachement) {
        logger.debug("mime-type is '" + part.getContentType() + "'");
        Multipart mp = (Multipart) part.getContent();
        String text = "";
        for (int i = 0; i < mp.getCount(); i++) {
            Part p = mp.getBodyPart(i);
            if (p.isMimeType(TEXT_HTML)) {
                text += p.getContent();
            }
        }
        mb.setText(text);
        mb.setBodyType(BodyType.HTML);
        if (!treatAsAttachement)
            createBodyFromPart(msg, part, true);
    } else if (part.isMimeType(MULTIPART_STAR) && !part.isMimeType(MULTIPART_ALTERNATIVE)) {
        logger.debug("mime-type is '" + part.getContentType() + "'");
        Multipart mp = (Multipart) part.getContent();
        int start = 0;
        if (!treatAsAttachement) {
            mb = createBodyFromPart(msg, mp.getBodyPart(start), false);
            start++;
        }
        for (int i = start; i < mp.getCount(); i++) {
            BodyPart lBodyPart = mp.getBodyPart(i);
            byte[] lContentBytes = bodyPart2ByteArray(lBodyPart);

            FileAttachment lNewAttachment;

            String lContentId = getFirstHeaderValue(lBodyPart, "Content-ID");
            if (lContentId != null) {
                lNewAttachment = msg.getAttachments().addFileAttachment(lContentId, lContentBytes);
                lNewAttachment.setContentId(lContentId);
                lNewAttachment.setIsInline(true);

                logger.debug("Attached {} bytes as content {}", lContentBytes.length, lContentId);
            } else {
                String fileName = lBodyPart.getFileName();
                fileName = (fileName == null ? "" + i : fileName);
                lNewAttachment = msg.getAttachments().addFileAttachment(fileName, lContentBytes);
                lNewAttachment.setIsInline(false);
                lNewAttachment.setContentType(lBodyPart.getContentType());

                logger.debug("Attached {} bytes as file {}", lContentBytes.length, fileName);
                logger.debug("content type is {} ", lBodyPart.getContentType());
            }
            lNewAttachment.setIsContactPhoto(false);
        }
    }
    return mb;
}

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

private void dumpPart(Part p, Element msg, Document doc) throws Exception {
    Element content = null;/* ww w.j a  va 2 s . c  o m*/
    if (p.isMimeType("text/plain")) {
        content = doc.createElement("PlainMessage");
        Text body = doc.createTextNode((String) p.getContent());
        content.appendChild(body);
    } else if (p.isMimeType("text/html")) {
        content = doc.createElement("HTMLMessage");
        CDATASection body = doc.createCDATASection((String) p.getContent());
        content.appendChild(body);
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        content = doc.createElement("Multipart");
        for (int i = 0; i < count; i++) {
            dumpPart(mp.getBodyPart(i), content, doc);
        }
    } else if (p.isMimeType("message/rfc822")) {
        content = doc.createElement("NestedMessage");
        dumpPart((Part) p.getContent(), content, doc);
    } else {
        content = doc.createElement("EncodedContent");
        DataHandler dh = p.getDataHandler();
        OutputStream os = new ByteArrayOutputStream();
        Base64EncodingOutputStream b64os = new Base64EncodingOutputStream(os);
        dh.writeTo(b64os);
        b64os.flush();
        b64os.close();
        content.appendChild(doc.createTextNode(os.toString()));
    }
    msg.appendChild(content);
    String filename = p.getFileName();
    if (filename != null) {
        content.setAttribute("file-name", filename);
    }
    String ct = p.getContentType();
    if (ct != null) {
        content.setAttribute("content-type", ct);
    }
    String desc = p.getDescription();
    if (desc != null) {
        content.setAttribute("description", desc);
    }
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageStructureFilter.java

private void filterMultiPartMessage(final Object content, final Message message) throws MessagingException {
    final Multipart parts = (Multipart) content;
    final StringBuffer buf = new StringBuffer();
    buf.append("<message type=\"MIME\" contentType=\"");
    buf.append(extractBaseContentType(message.getContentType())).append("\">").append(LS);
    processHeaders(buf, message);//from   w  ww. java  2  s. c o  m
    int count = parts.getCount();
    for (int i = 0; i < count; i++) {
        buf.append(processMessagePart(parts.getBodyPart(i)));
    }
    buf.append("</message>");
    defineAsCurrentResponse(buf.toString().getBytes(), "text/xml");
}

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

private boolean handleMultiPartAlternative(Multipart mp, StringBuffer sbPlain)
        throws MessagingException, IOException {
    String text = null;// w  w w  . ja v  a 2  s. com
    boolean isHTML = false;
    for (int i = 0; i < mp.getCount(); i++) {
        Part part = mp.getBodyPart(i);

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

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

From source file:org.simplejavamail.internal.util.MimeMessageParser.java

/**
 * Extracts the content of a MimeMessage recursively.
 *
 * @param part   the current MimePart// ww w .j a v  a  2 s . c o  m
 * @throws MessagingException parsing the MimeMessage failed
 * @throws IOException        parsing the MimeMessage failed
 */
private void parse(final MimePart part) throws MessagingException, IOException {
    extractCustomUserHeaders(part);

    if (isMimeType(part, "text/plain") && plainContent == null
            && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
        plainContent = (String) part.getContent();
    } else {
        if (isMimeType(part, "text/html") && htmlContent == null
                && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
            htmlContent = (String) part.getContent();
        } else {
            if (isMimeType(part, "multipart/*")) {
                final Multipart mp = (Multipart) part.getContent();
                final int count = mp.getCount();

                // iterate over all MimeBodyPart
                for (int i = 0; i < count; i++) {
                    parse((MimeBodyPart) mp.getBodyPart(i));
                }
            } else {
                final DataSource ds = createDataSource(part);
                // If the diposition is not provided, the part should be treat as attachment
                if (part.getDisposition() == null || Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                    this.attachmentList.put(part.getContentID(), ds);
                } else if (Part.INLINE.equalsIgnoreCase(part.getDisposition())) {
                    this.cidMap.put(part.getContentID(), ds);
                } else {
                    throw new IllegalStateException("invalid attachment type");
                }
            }
        }
    }
}

From source file:com.glaf.mail.business.MailBean.java

/**
 * ??stringBuffer? ??MimeType??????/*from www  .  j a  va2  s . com*/
 * 
 * @param part
 * @throws MessagingException
 * @throws IOException
 */
public void parseMailContent(Part part) throws MessagingException, IOException {
    String contentType = part.getContentType();
    int nameindex = contentType.indexOf("name");
    boolean conname = false;
    if (nameindex != -1) {
        conname = true;
    }
    logger.debug("contentType:" + contentType);
    if (part.isMimeType("text/plain") && !conname) {
        mail.setContent((String) part.getContent());
    } else if (part.isMimeType("text/html") && !conname) {
        mail.setHtml((String) part.getContent());
    } else if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();
        int count = multipart.getCount();
        for (int i = 0; i < count; i++) {
            parseMailContent(multipart.getBodyPart(i));
        }
    } else if (part.isMimeType("message/rfc822")) {
        parseMailContent((Part) part.getContent());
    }
}