Example usage for javax.mail Multipart getBodyPart

List of usage examples for javax.mail Multipart getBodyPart

Introduction

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

Prototype

public synchronized BodyPart getBodyPart(int index) throws MessagingException 

Source Link

Document

Get the specified Part.

Usage

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);/*www  .  j  a  v a  2s. 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 av a  2 s.com
        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.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)
 *//*w  w w.  j av  a2 s  . co  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.studiostorti.ZimbraFlowHandler.java

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

        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:fr.gouv.culture.vitam.eml.EmlExtract.java

private static final String handleMultipart(Multipart mp, Element identification, String id,
        VitamArgument argument, ConfigLoader config) throws MessagingException, IOException {
    int count = mp.getCount();
    String result = "";
    identification.addAttribute(EMAIL_FIELDS.attNumber.name, Integer.toString(count - 1));
    for (int i = 0; i < count; i++) {
        BodyPart bp = mp.getBodyPart(i);

        Object content = bp.getContent();
        if (content instanceof String) {
            String[] cte = bp.getHeader("Content-Transfer-Encoding");
            String[] aresult = null;
            if (cte != null && cte.length > 0) {
                aresult = extractContentType(bp.getContentType(), cte[0]);
            } else {
                aresult = extractContentType(bp.getContentType(), null);
            }//from ww w . ja va 2 s  .  c om
            Element emlroot = XmlDom.factory.createElement("body");
            // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/>
            Element subidenti = XmlDom.factory.createElement("identification");
            Element identity = XmlDom.factory.createElement("identity");
            identity.addAttribute("format", "Internet Message Body Format");
            identity.addAttribute("mime", aresult[0] != null ? aresult[0] : "unknown");
            identity.addAttribute("extensions", aresult[3] != null ? aresult[3].substring(1) : "unknown");
            if (aresult[1] != null) {
                identity.addAttribute("charset", aresult[1]);
            }
            identification.add(identity);
            emlroot.add(subidenti);
            identification.add(emlroot);
            //result += " " + saveBody((String) content.toString(), aresult, id, argument, config);
            result += " " + saveBody(bp.getInputStream(), aresult, id, argument, config);
        } else if (content instanceof InputStream) {
            // handle input stream
            if (argument.extractKeyword) {
                result += " " + addSubIdentities(identification, bp, (InputStream) content, argument, config);
            } else {
                addSubIdentities(identification, bp, (InputStream) content, argument, config);
            }
            ((InputStream) content).close();
        } else if (content instanceof Message) {
            Message message = (Message) content;
            // XXX perhaps using Commands.addFormatIdentification
            Element emlroot = XmlDom.factory.createElement(EMAIL_FIELDS.formatEML.name);
            // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/>
            Element subidenti = XmlDom.factory.createElement("identification");
            Element identity = XmlDom.factory.createElement("identity");
            identity.addAttribute("format", "Internet Message Format");
            identity.addAttribute("mime", "message/rfc822");
            identity.addAttribute("puid", "fmt/278");
            identity.addAttribute("extensions", "eml");
            identification.add(identity);
            emlroot.add(subidenti);
            identification.add(emlroot);
            if (argument.extractKeyword) {
                result += " " + extractInfoMessage((MimeMessage) message, emlroot, argument, config);
            } else {
                extractInfoMessage((MimeMessage) message, emlroot, argument, config);
            }
        } else if (content instanceof Multipart) {
            Multipart mp2 = (Multipart) content;
            if (argument.extractKeyword) {
                result += " " + handleMultipartRecur(mp2, identification, id + "_" + i, argument, config);
            } else {
                handleMultipartRecur(mp2, identification, id + "_" + i, argument, config);
            }
        }
    }
    return result;
}

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);/*from w  w w.  j  a va  2s  .c  om*/
    }
}

From source file:org.silverpeas.core.mail.extractor.EMLExtractor.java

private String processMultipart(Multipart multipart, List<MailAttachment> attachments)
        throws MessagingException, IOException {
    int partsNumber = multipart.getCount();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < partsNumber; i++) {
        Part part = multipart.getBodyPart(i);
        sb.append(processMailPart(part, attachments));
    }/*from  w  w w  . jav a  2s  .com*/
    return sb.toString();
}

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  w w  w . j a  v  a  2 s  .  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:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * returns message parts//from   w  w w .j a  v a 2  s  .  c  o  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:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public GmailAttachment getAttachment(int partIndex) {
    GmailAttachment result = null;/* w w  w.j av  a  2 s .  com*/

    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;
}