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:mitm.application.djigzo.ca.PFXMailBuilderTest.java

@Test
public void testReplacePFXSendSMSFalse() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);//from  w  ww . j  a v  a 2  s .c o m

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);
    builder.addProperty("sendSMS", false);

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFXSendSMSFalse.eml"));

    Multipart mp;

    mp = (Multipart) message.getContent();

    BodyPart textPart = mp.getBodyPart(0);

    assertTrue(textPart.isMimeType("text/plain"));

    String body = (String) textPart.getContent();

    assertFalse(body.contains("was sent to you by SMS"));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}

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

@Test
public void testReplacePFXSendSMSTrue() throws Exception {
    byte[] pfx = IOUtils.toByteArray(new FileInputStream(testPFX));

    PFXMailBuilder builder = new PFXMailBuilder(IOUtils.toString(new FileInputStream(templateFile)),
            templateBuilder);//from  ww  w. j a v a  2s .  com

    String from = "123@test.com";

    builder.setFrom(new InternetAddress(from, "test user"));
    builder.setPFX(pfx);
    builder.addProperty("sendSMS", true);
    builder.addProperty("phoneNumberAnonymized", "1234***");
    builder.addProperty("id", "0987");

    MimeMessage message = builder.createMessage();

    assertNotNull(message);

    MailUtils.writeMessage(message, new File(tempDir, "testReplacePFXSendSMSTrue.eml"));

    Multipart mp;

    mp = (Multipart) message.getContent();

    BodyPart textPart = mp.getBodyPart(0);

    assertTrue(textPart.isMimeType("text/plain"));

    String body = (String) textPart.getContent();

    assertTrue(body.contains("was sent to you by SMS"));

    /*
     * Check if the PFX has really been replaced
     */
    byte[] newPFX = getPFX(message);

    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new ByteArrayInputStream(newPFX), "test".toCharArray());

    assertEquals(22, keyStore.size());
}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

private static final String handleMultipartRecur(Multipart mp, Element identification, String id,
        VitamArgument argument, ConfigLoader config) throws MessagingException, IOException {
    int count = mp.getCount();
    String result = "";
    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 www  . j  av  a  2 s .  com*/
            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);
            // ignore string
        } 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);
            }
        } else if (content instanceof Message) {
            Message message = (Message) content;
            if (argument.extractKeyword) {
                result += " " + handleMessageRecur(message, identification, id + "_" + i, argument, config);
            } else {
                handleMessageRecur(message, identification, id + "_" + i, 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:ch.algotrader.util.mail.EmailTransformer.java

/**
 * Parses any {@link Multipart} instances that contains attachments
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 * @throws MessagingException//w  w  w .  jav a  2 s.co  m
 */
public void handleMultipart(Multipart multipart, List<EmailFragment> emailFragments) throws MessagingException {

    final int count = multipart.getCount();

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

        BodyPart bodyPart = multipart.getBodyPart(i);
        String filename = bodyPart.getFileName();
        String disposition = bodyPart.getDisposition();

        if (filename == null && bodyPart instanceof MimeBodyPart) {
            filename = ((MimeBodyPart) bodyPart).getContentID();
        }

        if (disposition == null) {

            //ignore message body

        } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)) {

            try {
                try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        BufferedInputStream bis = new BufferedInputStream(bodyPart.getInputStream())) {

                    IOUtils.copy(bis, bos);

                    emailFragments.add(new EmailFragment(filename, bos.toByteArray()));

                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info(String.format("processing file: %s", new Object[] { filename }));
                    }

                }

            } catch (IOException e) {
                throw new MessagingException("error processing streams", e);
            }

        } else {
            throw new MessagingException("unkown disposition " + disposition);
        }
    }
}

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

/**
 * Calculate the result.//ww w .jav a 2  s. c  om
 *
 * @param message
 * @return The result
 */
protected String performOperation(final Message message) throws MessagingException {
    if (StringUtils.isEmpty(getPartIndex())) {
        return arrayToString(message.getHeader(getHeaderName()));
    }
    final Object content;
    try {
        content = message.getContent();
    } catch (IOException e) {
        LOG.error("Error processing email message: ", e);
        throw new MessagingException("Error processing email message: " + e.getMessage());
    }
    if (content instanceof Multipart) {
        final Multipart mp = (Multipart) content;
        final int part = ConversionUtil.convertToInt(getPartIndex(), 0);
        if (part >= mp.getCount()) {
            throw new StepFailedException("PartIndex too large.", this);
        }
        return arrayToString(mp.getBodyPart(part).getHeader(getHeaderName()));
    }
    throw new StepFailedException("PartIndex supplied for a non-MultiPart message.", this);
}

From source file:it.greenvulcano.gvesb.virtual.smtp.SMTPCallOperationTest.java

/**
  * Tests email send//from w  w  w.  ja v  a2 s  . c  om
  *
  * @throws Exception
  *         if any error occurs
  */
public final void testSendEmail() throws Exception {
    Node node = XMLConfig.getNode("GVCore.xml", "//*[@name='SendEmail']");
    CallOperation op = new SMTPCallOperation();
    op.init(node);

    GVBuffer gvBuffer = new GVBuffer(TEST_SYSTEM, TEST_SERVICE);
    gvBuffer.setObject(TEST_MESSAGE);
    gvBuffer.setProperty("MAIL_SENDER", "SENDER ADDITIONAL INFO");

    op.perform(gvBuffer);

    //assertTrue(server.waitForIncomingEmail(5000, 1));

    Message[] messages = server.getReceivedMessages();
    assertEquals(1, messages.length);
    Message email = messages[0];
    Multipart mp = (Multipart) email.getContent();
    assertEquals("Notifica SendEmail", email.getSubject());
    assertEquals(TEST_MESSAGE, 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 SendEmail", email.getHeader("Subject")[0]);
    assertEquals("1", email.getHeader("X-Priority")[0]);
}

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

/**
 * Get text from message/*from   w  w  w  . jav  a  2  s .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.xmlactions.email.EMailParser.java

private void showPart(Part part) throws IOException, MessagingException {

    log.info("\n\n\nshowPart ==>>");
    log.info("part.toString():" + part.toString());
    log.info("part.getContent():" + (part.getFileName() == null ? part.getContent().toString() : "Attachment"));
    log.info("part.getContentType():" + part.getContentType());
    log.info("part.getFilename():" + part.getFileName());
    log.info("part.isAttachment:" + part.getFileName());
    log.info("part.isMessage:" + (part.getContent() instanceof Message));
    Object obj = part.getContent();
    if (obj instanceof Multipart) {
        log.info("MultiPart");

        Multipart mmp = (Multipart) obj;
        for (int i = 0; i < mmp.getCount(); i++) {
            Part bodyPart = mmp.getBodyPart(i);
            showPart(bodyPart);/*from   w  w  w . j a v a 2  s .c om*/
        }
    } else if (obj instanceof Part) {
        showPart((Part) obj);
    } else {
        log.info("=== Add Part ===");
        log.info((String) (part.getFileName() != null ? "isAttachment" : part.getContent()));
        // log.info("not recognised class:" + obj.getClass().getName() +
        // "\n" + obj);
    }
    log.info("<<== showPart");
}

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

/**
 * Add attachments to an imported mail./*  w w  w  .j a v a 2s .c  o  m*/
 */
public static void addAttachments(String token, com.openkm.bean.Mail mail, Part p, String userId)
        throws MessagingException, IOException, UnsupportedMimeTypeException, FileSizeExceededException,
        UserQuotaExceededException, VirusDetectedException, ItemExistsException, PathNotFoundException,
        AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException {
    if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();

        for (int i = 1; i < count; i++) {
            BodyPart bp = mp.getBodyPart(i);

            if (bp.getFileName() != null) {
                String name = MimeUtility.decodeText(bp.getFileName());
                String fileName = FileUtils.getFileName(name);
                String fileExtension = FileUtils.getFileExtension(name);
                String testName = name;

                // Test if already exists a document with the same name in the mail
                for (int j = 1; OKMRepository.getInstance().hasNode(token,
                        mail.getPath() + "/" + testName); j++) {
                    // log.info("Trying with: {}", testName);
                    testName = fileName + " (" + j + ")." + fileExtension;
                }

                Document attachment = new Document();
                String mimeType = MimeTypeConfig.mimeTypes.getContentType(bp.getFileName().toLowerCase());
                attachment.setMimeType(mimeType);
                attachment.setPath(mail.getPath() + "/" + testName);
                InputStream is = bp.getInputStream();

                if (Config.REPOSITORY_NATIVE) {
                    new DbDocumentModule().create(token, attachment, is, bp.getSize(), userId);
                } else {
                    new JcrDocumentModule().create(token, attachment, is, userId);
                }

                is.close();
            }
        }
    }
}

From source file:it.greenvulcano.gvesb.virtual.smtp.SMTPCallOperationTest.java

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

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

    op.perform(gvBuffer);

    Message[] messages = server.getReceivedMessages();
    assertEquals(1, messages.length);
    Message email = messages[0];
    Multipart mp = (Multipart) email.getContent();
    assertEquals("Notifica SendEmailBufferAttach", 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(mp.getBodyPart(0)));
    System.out.println("---------MAIL DUMP: END");
    assertEquals("Notifica SendEmailBufferAttach", email.getHeader("Subject")[0]);
    assertEquals("Current Data", mp.getBodyPart(1).getFileName());
}