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:com.liferay.mail.imap.IMAPAccessor.java

protected void getParts(long userId, StringBundler bodyPlain, StringBundler bodyHtml, String contentPath,
        Part part, List<MailFile> mailFiles) throws IOException, MessagingException {

    String fileName = part.getFileName();
    Object content = part.getContent();

    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;

        for (int i = 0; i < multipart.getCount(); i++) {
            Part curPart = multipart.getBodyPart(i);

            getParts(userId, bodyPlain, bodyHtml,
                    contentPath.concat(StringPool.PERIOD).concat(String.valueOf(i)), curPart, mailFiles);
        }/*  ww w  .  j a  v a 2 s  . c  om*/
    } else if (Validator.isNull(fileName)) {
        String contentType = StringUtil.toLowerCase(part.getContentType());

        if (contentType.startsWith(ContentTypes.TEXT_PLAIN)) {
            bodyPlain.append(content.toString().replaceAll("\r\n", "<br />"));
        } else if (contentType.startsWith(ContentTypes.TEXT_HTML)) {
            bodyHtml.append(HtmlContentUtil.getInlineHtml(content.toString()));
        }
        //else if (contentType.startsWith(ContentTypes.MESSAGE_RFC822)) {
        //}
    } else {
        MailFile mailFile = new MailFile(contentPath.concat(StringPool.PERIOD).concat("-1"), fileName,
                part.getSize());

        mailFiles.add(mailFile);
    }
}

From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java

public void sign(String signingAlgorithm, String digestOID) throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    mailetConfig.setInitParameter("algorithmAttribute", "signingAlgo");

    SMIMESign mailet = new SMIMESign();

    mailet.init(mailetConfig);//from  www .  j a va2 s .c om

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml"));

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("m.brinkers@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    mail.setAttribute("signingAlgo", signingAlgorithm);

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    MailUtils.writeMessage(mail.getMessage(), new File(tempDir, "testDefaultSettings.eml"));

    assertEquals(SMIMEHeader.DETACHED_SIGNATURE_TYPE,
            SMIMEUtils.dissectSigned((Multipart) mail.getMessage().getContent())[1].getContentType());

    SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), null, "BC");

    assertEquals(SMIMEType.SIGNED, inspector.getSMIMEType());
    assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(mail.getMessage()));
    assertEquals(3, inspector.getSignedInspector().getCertificates().size());
    assertEquals(1, inspector.getSignedInspector().getSigners().size());
    assertEquals(digestOID, inspector.getSignedInspector().getSigners().get(0).getDigestAlgorithmOID());

    // check that no headers are signed. Only a content-type header should be added to the part
    Multipart mp = (Multipart) mail.getMessage().getContent();

    assertEquals(2, mp.getCount());

    BodyPart part = mp.getBodyPart(0);

    Enumeration<?> e = part.getNonMatchingHeaders(new String[] { "content-type" });

    assertFalse(e.hasMoreElements());
}

From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java

@Test
public void testProtectedHeaders() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SMIMESign mailet = new SMIMESign();

    mailetConfig.setInitParameter("protectedHeader", "subject,to,from");

    mailet.init(mailetConfig);//from   w  ww .  j  ava2  s  . c om

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml"));

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("m.brinkers@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    MailUtils.writeMessage(mail.getMessage(), new File(tempDir, "testProtectedHeaders.eml"));

    assertEquals(SMIMEHeader.DETACHED_SIGNATURE_TYPE,
            SMIMEUtils.dissectSigned((Multipart) mail.getMessage().getContent())[1].getContentType());

    // check if some headers are signed
    Multipart mp = (Multipart) mail.getMessage().getContent();

    assertEquals(2, mp.getCount());

    BodyPart part = mp.getBodyPart(0);

    // there should be 3 non content-type headers
    Enumeration<?> e = part.getNonMatchingHeaders(new String[] { "content-type" });

    int count = 0;
    while (e.hasMoreElements()) {
        e.nextElement();
        count++;
    }
    assertEquals(3, count);

    assertEquals("test simple message", StringUtils.join(part.getHeader("subject"), ","));
    assertEquals("test@example.com", StringUtils.join(part.getHeader("from"), ","));
    assertEquals("test@example.com", StringUtils.join(part.getHeader("to"), ","));
}

From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java

@Test
public void testDefaultSettings() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SMIMESign mailet = new SMIMESign();

    mailet.init(mailetConfig);//from  w  w  w .j  a va 2s  . c  o  m

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml"));

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("m.brinkers@pobox.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    MailUtils.writeMessage(mail.getMessage(), new File(tempDir, "testDefaultSettings.eml"));

    assertEquals(SMIMEHeader.DETACHED_SIGNATURE_TYPE,
            SMIMEUtils.dissectSigned((Multipart) mail.getMessage().getContent())[1].getContentType());

    SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), null, "BC");

    assertEquals(SMIMEType.SIGNED, inspector.getSMIMEType());
    assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(mail.getMessage()));
    assertEquals(3, inspector.getSignedInspector().getCertificates().size());
    assertEquals("1C1C1CF46CC9233B23391A3B9BEF558969567091", X509CertificateInspector
            .getThumbprint(inspector.getSignedInspector().getCertificates().get(0), Digest.SHA1));
    assertEquals("D8F8E5B92E651B1E3EF93B5493EACDE4C13AFEE0", X509CertificateInspector
            .getThumbprint(inspector.getSignedInspector().getCertificates().get(1), Digest.SHA1));
    assertEquals("69D7FFAF26BD5E9E4F42083BCA077BFAA8398593", X509CertificateInspector
            .getThumbprint(inspector.getSignedInspector().getCertificates().get(2), Digest.SHA1));
    assertEquals(1, inspector.getSignedInspector().getSigners().size());
    assertEquals(Digest.SHA1.getOID(),
            inspector.getSignedInspector().getSigners().get(0).getDigestAlgorithmOID());

    // check that no headers are signed. Only a content-type header should be added to the part
    Multipart mp = (Multipart) mail.getMessage().getContent();

    assertEquals(2, mp.getCount());

    BodyPart part = mp.getBodyPart(0);

    Enumeration<?> e = part.getNonMatchingHeaders(new String[] { "content-type" });

    assertFalse(e.hasMoreElements());
}

From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java

@Test
public void testSignBuildPath() throws Exception {
    AutoTransactDelegator proxy = AutoTransactDelegator.createProxy();

    /*//from www . j a v  a2s. co m
     * Find a certificate with critical EMAILPROTECTION extension
     */
    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("1178C3B653829E895ACB7100EB1F627"));
    selector.setIssuer("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL");

    List<KeyAndCertificate> keyAndCertificates = proxy.getKeyAndCertificates(selector);

    assertEquals(1, keyAndCertificates.size());

    proxy.setUserSigningKeyAndCertificate("test@example.com", keyAndCertificates.get(0));

    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SMIMESign mailet = new SMIMESign();

    mailet.init(mailetConfig);

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-message.eml"));

    mail.setMessage(message);

    Set<MailAddress> recipients = new HashSet<MailAddress>();

    recipients.add(new MailAddress("recipient@example.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("test@example.com"));

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    MailUtils.writeMessage(mail.getMessage(), new File(tempDir, "testDefaultSettings.eml"));

    assertEquals(SMIMEHeader.DETACHED_SIGNATURE_TYPE,
            SMIMEUtils.dissectSigned((Multipart) mail.getMessage().getContent())[1].getContentType());

    SMIMEInspector inspector = new SMIMEInspectorImpl(mail.getMessage(), null, "BC");

    assertEquals(SMIMEType.SIGNED, inspector.getSMIMEType());
    assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(mail.getMessage()));
    assertEquals(3, inspector.getSignedInspector().getCertificates().size());
    assertEquals("F18CC8973F9AB82A6C47448282849A72416B6DAB", X509CertificateInspector
            .getThumbprint(inspector.getSignedInspector().getCertificates().get(0), Digest.SHA1));
    assertEquals("D8F8E5B92E651B1E3EF93B5493EACDE4C13AFEE0", X509CertificateInspector
            .getThumbprint(inspector.getSignedInspector().getCertificates().get(1), Digest.SHA1));
    assertEquals("69D7FFAF26BD5E9E4F42083BCA077BFAA8398593", X509CertificateInspector
            .getThumbprint(inspector.getSignedInspector().getCertificates().get(2), Digest.SHA1));
    assertEquals(1, inspector.getSignedInspector().getSigners().size());
    assertEquals(Digest.SHA1.getOID(),
            inspector.getSignedInspector().getSigners().get(0).getDigestAlgorithmOID());

    // check that no headers are signed. Only a content-type header should be added to the part
    Multipart mp = (Multipart) mail.getMessage().getContent();

    assertEquals(2, mp.getCount());

    BodyPart part = mp.getBodyPart(0);

    Enumeration<?> e = part.getNonMatchingHeaders(new String[] { "content-type" });

    assertFalse(e.hasMoreElements());
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected Part getPart(Part part, String contentPath) throws IOException, MessagingException {

    int index = GetterUtil.getInteger(StringUtil.split(contentPath.substring(1), StringPool.PERIOD)[0]);

    if (!(part.getContent() instanceof Multipart)) {
        return part;
    }/*from  w  ww . j av  a  2  s.co m*/

    Multipart multipart = (Multipart) part.getContent();

    for (int i = 0; i < multipart.getCount(); i++) {
        if (i != index) {
            continue;
        }

        String prefix = String.valueOf(index).concat(StringPool.PERIOD);

        return getPart(multipart.getBodyPart(i), contentPath.substring(prefix.length()));
    }

    return part;
}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * Handle a multipart of a email message. May recursively call handleMultipart or
 * handlePart./* w  w  w.  j a  va  2  s .  c o  m*/
 *
 * @param multipart The multipart to handle.
 * @throws MessagingException
 * @throws IOException
 */
private void handleMultipart(Multipart multipart) throws MessagingException, IOException {

    for (int i = 0, n = multipart.getCount(); i < n; i++) {
        Part p = multipart.getBodyPart(i);
        if (p instanceof Multipart) {
            handleMultipart((Multipart) p);
        } else {
            handlePart(multipart.getBodyPart(i));
        }
    }
}

From source file:immf.SendMailBridge.java

private void parseMultipart(SenderMail sendMail, Multipart mp, String subtype, String parentSubtype)
        throws IOException {
    String contentType = mp.getContentType();
    log.info("Multipart ContentType:" + contentType);

    try {//www.j a  v a 2 s .  com
        int count = mp.getCount();
        log.info("count " + count);

        boolean hasInlinePart = false;
        if (subtype.equalsIgnoreCase("mixed")) {
            for (int i = 0; i < count; i++) {
                String d = mp.getBodyPart(i).getDisposition();
                if (d != null && d.equalsIgnoreCase(Part.INLINE))
                    hasInlinePart = true;
            }
        }
        if (hasInlinePart) {
            log.info("parseBodypart(Content-Disposition:inline)");
            for (int i = 0; i < count; i++) {
                parseBodypartmixed(sendMail, mp.getBodyPart(i), subtype, parentSubtype);
            }
            if (sendMail.getHtmlContent() != null) {
                sendMail.addHtmlContent("</body>");
            }
            if (sendMail.getHtmlWorkingContent() != null) {
                sendMail.addHtmlWorkingContent("</body>");
            }
        } else {
            for (int i = 0; i < count; i++) {
                parseBodypart(sendMail, mp.getBodyPart(i), subtype, parentSubtype);
            }
        }
    } catch (Exception e) {
        log.error("parse multipart error.", e);
        //throw new IOException("MimeMultiPart error."+e.getMessage(),e);
    }
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!//from ww w  . ja v a 2  s .  co m
 *
 * @param part DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
private static int getPartSize(Part part) {
    int size = 0;

    try {
        boolean attachIt = true;
        ContentType xctype = MessageUtilities.getContentType(part);
        ContentDisposition xcdisposition = MessageUtilities.getContentDisposition(part);

        if (xctype.match("multipart/*")) {
            attachIt = false;

            Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part);

            int xparts = xmulti.getCount();

            for (int xindex = 0; xindex < xparts; xindex++) {
                MessageUtilities.getPartSize(xmulti.getBodyPart(xindex));
            }
        } else if (xctype.match("text/plain")) {
            if (xcdisposition.match("inline")) {
                attachIt = false;
                size += sizeInline(part);
            }
        } else if (xctype.match("text/html")) {
            if (xcdisposition.match("inline")) {
                attachIt = false;
                size += sizeInline(part);
            }
        }

        if (attachIt) {
            size += IOUtils.toByteArray(part.getInputStream()).length;
        }
    } catch (MessagingException e) {
    } catch (IOException e) {
    } catch (Exception e) {
    }

    return size;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Get a textual description of a part./*from  w ww  .  j a va  2 s . co  m*/
 *
 * @param part The part to interogate
 * @param buf a string buffer for the description
 * @param prefix a prefix for each line of the description
 * @param recurse boolean specifying wether to recurse through sub-parts or
 *        not
 *
 * @return StringBuffer containing the description of the part
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static StringBuffer getPartDescription(Part part, StringBuffer buf, String prefix, boolean recurse)
        throws MessagingException {
    if (buf == null) {
        return buf;
    }

    ContentType xctype = MessageUtilities.getContentType(part);

    String xvalue = xctype.toString();
    buf.append(prefix);
    buf.append("Content-Type: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDisposition();
    buf.append(prefix);
    buf.append("Content-Disposition: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDescription();
    buf.append(prefix);
    buf.append("Content-Description: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = MessageUtilities.getFileName(part);
    buf.append(prefix);
    buf.append("Content-Filename: ");
    buf.append(xvalue);
    buf.append('\n');

    if (part instanceof MimePart) {
        MimePart xmpart = (MimePart) part;
        xvalue = xmpart.getContentID();
        buf.append(prefix);
        buf.append("Content-ID: ");
        buf.append(xvalue);
        buf.append('\n');

        String[] langs = xmpart.getContentLanguage();

        if (langs != null) {
            buf.append(prefix);
            buf.append("Content-Language: ");

            for (int pi = 0; pi < langs.length; ++pi) {
                if (pi > 0) {
                    buf.append(", ");
                }

                buf.append(xvalue);
            }

            buf.append('\n');
        }

        xvalue = xmpart.getContentMD5();
        buf.append(prefix);
        buf.append("Content-MD5: ");
        buf.append(xvalue);
        buf.append('\n');

        xvalue = xmpart.getEncoding();
        buf.append(prefix);
        buf.append("Content-Encoding: ");
        buf.append(xvalue);
        buf.append('\n');
    }

    buf.append('\n');

    if (recurse && xctype.match("multipart/*")) {
        Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part);

        int xparts = xmulti.getCount();

        for (int xindex = 0; xindex < xparts; xindex++) {
            MessageUtilities.getPartDescription(xmulti.getBodyPart(xindex), buf, (prefix + "   "), true);
        }
    }

    return buf;
}