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:it.greenvulcano.gvesb.virtual.smtp.SMTPCallOperationTest.java

/**
 * Tests email send//from  w  w w.j  a  v  a2s .  co m
 *
 * @throws Exception
 *         if any error occurs
 */
public final void testSendEmailDynamicDest() throws Exception {
    Node node = XMLConfig.getNode("GVCore.xml", "//*[@name='SendEmailDynamicDest']");
    CallOperation op = new SMTPCallOperation();
    op.init(node);

    GVBuffer gvBuffer = new GVBuffer(TEST_SYSTEM, TEST_SERVICE);
    gvBuffer.setObject(TEST_MESSAGE);

    gvBuffer.setProperty("GV_SMTP_TO", "test1@gv.com");
    gvBuffer.setProperty("GV_SMTP_CC", "test2@gv.com");
    gvBuffer.setProperty("GV_SMTP_BCC", "test3@gv.com");

    op.perform(gvBuffer);

    Message[] messages = server.getReceivedMessages();
    assertEquals(3, messages.length);
    Message email = messages[0];
    Multipart mp = (Multipart) email.getContent();
    assertEquals("Notifica SendEmailDynamicDest", email.getSubject());
    assertEquals(TEST_MESSAGE_1, GreenMailUtil.getBody(mp.getBodyPart(0)));

    System.out.println("---------MAIL DUMP: START");
    System.out.println("Headers:\n" + GreenMailUtil.getHeaders(email));
    System.out.println("---------");
    System.out.println("Body:\n" + GreenMailUtil.getBody(email));
    System.out.println("---------MAIL DUMP: END");
    assertEquals("Notifica SendEmailDynamicDest", email.getHeader("Subject")[0]);
    assertEquals("test1@gv.com", email.getHeader("To")[0]);
    assertEquals("test2@gv.com", email.getHeader("Cc")[0]);
}

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

private String getBody(Multipart multipart) throws MessagingException, IOException {
    int partsNumber = multipart.getCount();
    String body = "";
    for (int i = 0; i < partsNumber; i++) {
        Part part = multipart.getBodyPart(i);
        if (part.isMimeType(MimeTypes.HTML_MIME_TYPE)) {
            // if present, return always HTML part
            return (String) part.getContent();
        } else if (part.isMimeType(MimeTypes.PLAIN_TEXT_MIME_TYPE)) {
            body = WebEncodeHelper.javaStringToHtmlParagraphe((String) part.getContent());
        } else if (part.getContent() instanceof Multipart) {
            return getBody((Multipart) part.getContent());
        }//w  w  w.j  a  v  a2s  .  c o  m
    }
    return body;
}

From source file:org.silverpeas.util.mail.EMLExtractor.java

private String getBody(Multipart multipart) throws MessagingException, IOException {
    int partsNumber = multipart.getCount();
    String body = "";
    for (int i = 0; i < partsNumber; i++) {
        Part part = multipart.getBodyPart(i);
        if (part.isMimeType(MimeTypes.HTML_MIME_TYPE)) {
            // if present, return always HTML part
            return (String) part.getContent();
        } else if (part.isMimeType(MimeTypes.PLAIN_TEXT_MIME_TYPE)) {
            body = EncodeHelper.javaStringToHtmlParagraphe((String) part.getContent());
        } else if (part.getContent() instanceof Multipart) {
            return getBody((Multipart) part.getContent());
        }//from w  ww  .j av  a 2s. c o  m
    }
    return body;
}

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;//  w  w  w .ja  va2 s . c o  m

    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:com.cubusmail.server.services.RetrieveImageServlet.java

/**
 * @param parent// w ww .java2s . co  m
 * @return
 */
private Part findImagePart(Part parent) {

    try {
        if (MessageUtils.isImagepart(parent)) {
            return parent;
        } else if (parent.isMimeType("multipart/*")) {
            Multipart mp;
            mp = (Multipart) parent.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                Part subPart = findImagePart(mp.getBodyPart(i));
                if (subPart != null) {
                    return subPart;
                }
            }
        }
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return null;
}

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

private void extractMultiPartMessage(final Multipart parts, final int partIndex) throws MessagingException {
    try {/*from  w w w.  j av  a  2  s . c  om*/
        if (partIndex >= parts.getCount()) {
            throw new StepFailedException("PartIndex too large.", this);
        }
        final BodyPart part = parts.getBodyPart(partIndex);
        final String contentType = part.getContentType();
        if (!StringUtils.isEmpty(getContentType()) && !contentType.equals(getContentType())) {
            throw new MessagingException("Actual contentType of '" + contentType
                    + "' did not match expected contentType of '" + fContentType + "'");
        }
        final String disp = part.getDisposition();
        final String filename = part.getFileName();
        final InputStream inputStream = part.getInputStream();
        if (Part.ATTACHMENT.equals(disp)) {
            fFilename = filename;
        } else {
            fFilename = getClass().getName();
        }
        ContextHelper.defineAsCurrentResponse(getContext(), IOUtils.toString(inputStream), contentType,
                "http://" + fFilename);
    } catch (IOException e) {
        throw new MessagingException("Error extracting part: " + e.getMessage());
    }
}

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 ww .ja v a 2s .  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.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 ww w.j a v  a  2 s  . c o  m*/
            "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:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java

private boolean hasAttachment(Message message) throws MessagingException {
    if (message.getContentType().startsWith("multipart/")) {
        try {//from   w w  w.j ava  2s.c  o  m
            Object content;

            content = message.getContent();

            if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;
                if (mp.getCount() > 1) {
                    for (int i = 0; i < mp.getCount(); i++) {
                        String disp = mp.getBodyPart(i).getDisposition();
                        if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
                            return true;
                        }
                    }
                }

            }
        } catch (IOException e) {
            logger.error("Error while get content of message " + message.getMessageNumber());
        }

    }
    return false;
}

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 av a  2  s  .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);
            }
        }
    }

}