Example usage for javax.mail.internet MimeMessage isMimeType

List of usage examples for javax.mail.internet MimeMessage isMimeType

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage isMimeType.

Prototype

@Override
public boolean isMimeType(String mimeType) throws MessagingException 

Source Link

Document

Is this Part of the specified MIME type?

Usage

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

@Test
public void testDecryptOL2010WithMissingSKIInSubjectWorkaroundEnabled() throws Exception {
    boolean skiWorkaroundEnabled = SecurityConstants.isOutlook2010SKIWorkaroundEnabled();

    try {/*from w w w .  ja  v  a 2 s  . c o  m*/
        SecurityConstants.setOutlook2010SKIWorkaroundEnabled(true);

        importKeyStore(keyAndCertificateWorkflow,
                new File("test/resources/testdata/keys/outlook2010_cert_missing_subjkeyid.p12"), "");

        SMIMEHandler mailet = new SMIMEHandler();

        mailetConfig.setInitParameter("handledProcessor", "handled");

        mailet.init(mailetConfig);

        MockMail mail = new MockMail();

        MimeMessage message = MailUtils
                .loadMessage(new File(testBase, "mail/outlook2010_cert_missing_subjkeyid.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);

        assertEquals(1, sendMailEventListener.getMails().size());

        Mail newMail = sendMailEventListener.getMails().get(0);

        MimeMessage decrypted = newMail.getMessage();

        assertTrue(decrypted.isMimeType("text/plain"));
        assertEquals("A broken S/MIME encrypted message", decrypted.getSubject());
        assertEquals("<000c01cadd1e$d8e3b700$8aab2500$@Domain>", decrypted.getMessageID());
        assertEquals(message.getMessageID(), decrypted.getMessageID());
        assertEquals("3DES, Key size: 168", decrypted.getHeader("X-Djigzo-Info-Encryption-Algorithm-0", ","));
        assertEquals("//2219E504D5750B37D20CC930B14129E1A2E583B1/1.2.840.113549.1.1.1",
                decrypted.getHeader("X-Djigzo-Info-Encryption-Recipient-0-0", ","));
        assertEquals("Created with Outlook 2010 Beta (14.0.4536.1000)",
                StringUtils.trim((String) decrypted.getContent()));

        assertEquals(Mail.GHOST, mail.getState());
    } finally {
        SecurityConstants.setOutlook2010SKIWorkaroundEnabled(skiWorkaroundEnabled);
    }
}

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

private void checkEncryption(MimeMessage message, String password, boolean hasReplyLink) throws Exception {
    /*//from   w  ww.  jav  a 2s . co  m
     * The message should be a mime multipart mixed with two parts. The first part should be readable text
     * and the second part should be the encrypted PDF
     */
    assertTrue(message.isMimeType("multipart/mixed"));

    Multipart mp = (Multipart) message.getContent();

    assertEquals(2, mp.getCount());

    BodyPart textPart = mp.getBodyPart(0);

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

    BodyPart pdfPart = mp.getBodyPart(1);

    assertTrue(pdfPart.isMimeType("application/pdf"));

    PdfReader reader = new PdfReader(pdfPart.getInputStream(), password.getBytes(CharacterEncoding.US_ASCII));

    String firstPageContent = new String(reader.getPageContent(1), CharacterEncoding.US_ASCII);

    /*
     * We just check whether the raw content contains (Reply) or not.
     */
    if (hasReplyLink) {
        assertTrue(firstPageContent.contains("(Reply)"));

        assertTrue(((String) textPart.getContent()).contains("reply URL: http://127.0.0.1?env="));
    } else {
        assertFalse(firstPageContent.contains("(Reply)"));
    }
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * A method that executes the reading of data from the email account to the
 * RBNB server after all configuration of settings, connections to hosts,
 * and thread initiatizing occurs. This method contains the detailed code
 * for reading the data and interpreting the data files.
 *///from   w ww. jav a 2 s  .  c o  m
protected boolean execute() {
    logger.debug("StorXDispatcher.execute() called.");
    boolean failed = true; // indicates overall success of execute()
    boolean messageProcessed = false; // indicates per message success

    // declare the account properties that will be pulled from the
    // email.account.properties.xml file
    String accountName = "";
    String server = "";
    String username = "";
    String password = "";
    String protocol = "";
    String dataMailbox = "";
    String processedMailbox = "";
    String prefetch = "";

    // fetch data from each sensor in the account list
    List accountList = this.xmlConfiguration.getList("account.accountName");

    for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) {

        int aIndex = accountList.indexOf(aIterator.next());

        // populate the email connection variables from the xml properties
        // file
        accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName");
        server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server");
        username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username");
        password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password");
        protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol");
        dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox");
        processedMailbox = (String) this.xmlConfiguration
                .getProperty("account(" + aIndex + ").processedMailbox");
        prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch");

        logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName     : " + accountName + "\n"
                + "server          : " + server + "\n" + "username        : " + username + "\n"
                + "password        : " + password + "\n" + "protocol        : " + protocol + "\n"
                + "dataMailbox     : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n"
                + "prefetch        : " + prefetch + "\n");

        // get a connection to the mail server
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.partialfetch", prefetch);

        try {

            // create the imaps mail session
            this.mailSession = Session.getDefaultInstance(props, null);
            this.mailStore = mailSession.getStore(protocol);

        } catch (NoSuchProviderException nspe) {

            try {
                // pause for 10 seconds
                logger.debug(
                        "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry.");
                Thread.sleep(10000L);
                this.mailStore = mailSession.getStore(protocol);

            } catch (NoSuchProviderException nspe2) {

                logger.debug("There was an error connecting to the mail server. The " + "message was: "
                        + nspe2.getMessage());
                nspe2.printStackTrace();
                failed = true;
                return !failed;

            } catch (InterruptedException ie) {

                logger.debug("The thread was interrupted: " + ie.getMessage());
                failed = true;
                return !failed;

            }

        }

        try {

            this.mailStore.connect(server, username, password);

            // get folder references for the inbox and processed data box
            Folder inbox = mailStore.getFolder(dataMailbox);
            inbox.open(Folder.READ_WRITE);

            Folder processed = this.mailStore.getFolder(processedMailbox);
            processed.open(Folder.READ_WRITE);

            Message[] msgs;
            while (!inbox.isOpen()) {
                inbox.open(Folder.READ_WRITE);

            }
            msgs = inbox.getMessages();

            List<Message> messages = new ArrayList<Message>();
            Collections.addAll(messages, msgs);

            // sort the messages found in the inbox by date sent
            Collections.sort(messages, new Comparator<Message>() {

                public int compare(Message message1, Message message2) {
                    int value = 0;
                    try {
                        value = message1.getSentDate().compareTo(message2.getSentDate());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return value;

                }

            });

            logger.debug("Number of messages: " + messages.size());
            for (Message message : messages) {

                // Copy the message to ensure we have the full attachment
                MimeMessage mimeMessage = (MimeMessage) message;
                MimeMessage copiedMessage = new MimeMessage(mimeMessage);

                // determine the sensor serial number for this message
                String messageSubject = copiedMessage.getSubject();
                Date sentDate = copiedMessage.getSentDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

                // The subfolder of the processed mail folder (e.g. 2016-12);
                String destinationFolder = formatter.format(sentDate);
                logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber());
                String[] subjectParts = messageSubject.split("\\s");
                String loggerSerialNumber = "SerialNumber";
                if (subjectParts.length > 1) {
                    loggerSerialNumber = subjectParts[2];

                }

                // Do we have a data attachment? If not, there's no data to
                // process
                if (copiedMessage.isMimeType("multipart/mixed")) {

                    logger.debug("Message size: " + copiedMessage.getSize());

                    MimeMessageParser parser = new MimeMessageParser(copiedMessage);
                    try {
                        parser.parse();

                    } catch (Exception e) {
                        logger.error("Failed to parse the MIME message: " + e.getMessage());
                        continue;
                    }
                    ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only

                    logger.debug("Has attachments: " + parser.hasAttachments());
                    for (DataSource dataSource : parser.getAttachmentList()) {
                        if (StringUtils.isNotBlank(dataSource.getName())) {
                            logger.debug(
                                    "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType());

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(dataSource.getInputStream(), outputStream);
                            messageAttachment = ByteBuffer.wrap(outputStream.toByteArray());

                        }
                    }

                    // We now have the attachment and serial number. Parse the attachment 
                    // for the data components, look up the storXSource based on the serial 
                    // number, and push the data to the DataTurbine

                    // parse the binary attachment
                    StorXParser storXParser = new StorXParser(messageAttachment);

                    // iterate through the parsed framesMap and handle each
                    // frame
                    // based on its instrument type
                    BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap();

                    Collection frameCollection = framesMap.getAll("/frames/frame");
                    Iterator framesIterator = frameCollection.iterator();

                    while (framesIterator.hasNext()) {

                        BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next();

                        // logger.debug(frameMap.toXMLString(1000));

                        String frameType = (String) frameMap.get("type");
                        String sensorSerialNumber = (String) frameMap.get("serialNumber");

                        // handle each instrument type
                        if (frameType.equals("HDR")) {
                            logger.debug("This is a header frame. Skipping it.");

                        } else if (frameType.equals("STX")) {

                            try {

                                // handle StorXSource
                                StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the StorXSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("SBE")) {

                            try {

                                // handle CTDSource
                                CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber);

                                // process the data using the CTDSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NLB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NDB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else {

                            logger.debug("The frame type " + frameType + " is not recognized. Skipping it.");
                        }

                    } // end while()

                    if (this.sourceMap.get(loggerSerialNumber) != null) {

                        // Note: Use message (not copiedMessage) when setting flags 

                        if (!messageProcessed) {
                            logger.info("Failed to process message: " + "Message Number: "
                                    + message.getMessageNumber() + "  " + "Logger Serial:"
                                    + loggerSerialNumber);
                            // leave it in the inbox, flagged as seen (read)
                            message.setFlag(Flags.Flag.SEEN, true);
                            logger.debug("Saw message " + message.getMessageNumber());

                        } else {

                            // message processed successfully. Create a by-month sub folder if it doesn't exist
                            // Copy the message and flag it deleted
                            Folder destination = processed.getFolder(destinationFolder);
                            boolean created = destination.create(Folder.HOLDS_MESSAGES);
                            inbox.copyMessages(new Message[] { message }, destination);
                            message.setFlag(Flags.Flag.DELETED, true);
                            logger.debug("Deleted message " + message.getMessageNumber());
                        } // end if()

                    } else {
                        logger.debug("There is no configuration information for " + "the logger serial number "
                                + loggerSerialNumber + ". Please add the configuration to the "
                                + "email.account.properties.xml configuration file.");

                    } // end if()

                } else {
                    logger.debug("This is not a data email since there is no "
                            + "attachment. Skipping it. Subject: " + messageSubject);

                } // end if()

            } // end for()

            // expunge messages and close the mail server store once we're
            // done
            inbox.expunge();
            this.mailStore.close();

        } catch (MessagingException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                failed = true;
                return !failed;

            }
            logger.info(
                    "There was an error reading the mail message. The " + "message was: " + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IOException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me3) {
                failed = true;
                return !failed;

            }
            logger.info("There was an I/O error reading the message part. The " + "message was: "
                    + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IllegalStateException ese) {
            try {
                this.mailStore.close();

            } catch (MessagingException me4) {
                failed = true;
                return !failed;

            }
            logger.info("There was an error reading messages from the folder. The " + "message was: "
                    + ese.getMessage());
            failed = true;
            return !failed;

        } finally {

            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                logger.debug("Couldn't close the mail store: " + me2.getMessage());

            }

        }

    }

    return !failed;
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testClearSign() throws Exception {
    MimeMessage message = loadMessage("normal-message-with-attach.eml");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from");

    builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(),
            SMIMESigningAlgorithm.SHA1WITHRSA);

    builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain()));

    builder.sign(SMIMESignMode.CLEAR);// www .  ja  va  2s .com

    MimeMessage newMessage = builder.buildMessage();

    File file = new File(tempDir, "testClearSign.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage));

    checkForSourceHeaders(newMessage);

    File opensslOutputFile = new File(tempDir, "testClearSign-openssl.eml");

    verifyMessage(file, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

    assertTrue(newMessage.isMimeType("multipart/mixed"));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));

    // the message should contain the signed from, to and subject
    checkForEmbeddedHeaders(newMessage);
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testClearSignSimpleTextMessageLF() throws Exception {
    File mail = new File(testDir, "simple-text-message-LF.eml");

    /*/*from  w  ww . j  a v a2  s.  c  om*/
     * check to make sure the file does not contain CR
     */
    String body = IOUtils.toString(new FileInputStream(mail));

    assertFalse(body.contains("\r"));

    MimeMessage message = MailUtils.loadMessage(mail);

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from");

    builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(),
            SMIMESigningAlgorithm.SHA1WITHRSA);

    builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain()));

    builder.sign(SMIMESignMode.CLEAR);

    MimeMessage newMessage = builder.buildMessage();

    File file = new File(tempDir, "test-simple-text-message-signed-lf.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage));

    File opensslOutputFile = new File(tempDir, "test-simple-text-message-lf-openssl.eml");

    verifyMessage(file, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

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

    assertEquals("test@example.com", newMessage.getHeader("from", ","));
    assertEquals("test@example.com", newMessage.getHeader("to", ","));
    assertEquals("test simple message", newMessage.getHeader("subject", ","));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));

    String content = (String) newMessage.getContent();

    assertEquals("test", content.trim());
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testOpaqueSign() throws Exception {
    MimeMessage message = loadMessage("normal-message-with-attach.eml");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from");

    builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(),
            SMIMESigningAlgorithm.SHA1WITHRSA);

    builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain()));

    builder.sign(SMIMESignMode.OPAQUE);/*from  w  w  w.j a v  a  2s. co  m*/

    MimeMessage newMessage = builder.buildMessage();

    File file = new File(tempDir, "testOpaqueSign.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.OPAQUE_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage));

    checkForSourceHeaders(newMessage);

    File opensslOutputFile = new File(tempDir, "testOpaqueSign-openssl.eml");

    verifyMessage(file, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

    assertTrue(newMessage.isMimeType("multipart/mixed"));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));

    // the message should contain the signed from, to and subject
    checkForEmbeddedHeaders(newMessage);
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testClearSignAddEncryptionKeyPreference() throws Exception {
    MimeMessage message = loadMessage("simple-text-message.eml");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from");

    builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(),
            SMIMESigningAlgorithm.SHA1WITHRSA, (X509Certificate) privateKeyEntry.getCertificate());

    builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain()));

    builder.sign(SMIMESignMode.CLEAR);//from   w  w w  .  jav a2s  .c o  m

    MimeMessage newMessage = builder.buildMessage();

    File file = new File(tempDir, "test-signed-encryptionkeypreference-signed.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage));

    File opensslOutputFile = new File(tempDir, "test-signed-encryptionkeypreference-signed-openssl.eml");

    verifyMessage(file, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

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

    assertEquals("test@example.com", newMessage.getHeader("from", ","));
    assertEquals("test@example.com", newMessage.getHeader("to", ","));
    assertEquals("test simple message", newMessage.getHeader("subject", ","));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));

    String content = (String) newMessage.getContent();

    assertEquals("test", content.trim());
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testClearSignNoProtectedHeader() throws Exception {
    MimeMessage message = loadMessage("normal-message-with-attach.eml");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "");

    builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(),
            SMIMESigningAlgorithm.SHA1WITHRSA);

    builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain()));

    builder.sign(SMIMESignMode.CLEAR);// w  w  w .  j  a va  2 s  .com

    MimeMessage newMessage = builder.buildMessage();

    File file = new File(tempDir, "testClearSignNoProtectedHeader.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage));

    checkForSourceHeaders(newMessage);

    File opensslOutputFile = new File(tempDir, "testClearSignNoProtectedHeader-openssl.eml");

    verifyMessage(file, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

    assertTrue(newMessage.isMimeType("multipart/mixed"));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));

    assertNull(newMessage.getHeader("subject", ","));
    assertEquals("<test@example.com>", message.getHeader("to", ","));
    assertNull(newMessage.getHeader("from"));
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testClearSignUnknownContentType() throws Exception {
    MimeMessage message = loadMessage("unknown-content-type.eml");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message);

    builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(),
            SMIMESigningAlgorithm.SHA1WITHRSA, (X509Certificate) privateKeyEntry.getCertificate());

    builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain()));

    builder.sign(SMIMESignMode.CLEAR);//from w  w  w.  j a  v a  2 s. co m

    MimeMessage newMessage = builder.buildMessage();

    MailUtils.validateMessage(newMessage);

    File file = new File(tempDir, "test-signed-unknown-content-type.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage));

    File opensslOutputFile = new File(tempDir, "test-signed-unknown-content-type-openssl.eml");

    verifyMessage(file, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

    assertTrue(newMessage.isMimeType("application/xxx"));
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testClearSignMultipleSigners() throws Exception {
    MimeMessage message = loadMessage("normal-message-with-attach.eml");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from");

    builder.addSigner(privateKeyEntry.getPrivateKey(), (X509Certificate) privateKeyEntry.getCertificate(),
            SMIMESigningAlgorithm.SHA1WITHRSA);

    builder.addCertificates(CertificateUtils.getX509Certificates(privateKeyEntry.getCertificateChain()));

    PrivateKeyEntry md5Entry = (PrivateKeyEntry) keyStore.getEntry("md5Hash", passwd);

    builder.addSigner(md5Entry.getPrivateKey(), (X509Certificate) md5Entry.getCertificate(),
            SMIMESigningAlgorithm.MD5WITHRSA);

    builder.addCertificates(CertificateUtils.getX509Certificates(md5Entry.getCertificateChain()));

    builder.sign(SMIMESignMode.CLEAR);//w w w. j ava2s.c om

    MimeMessage newMessage = builder.buildMessage();

    File file = new File(tempDir, "testClearSignMultipleSigners.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.CLEAR_SIGNED, SMIMEHeader.getSMIMEContentType(newMessage));

    checkForSourceHeaders(newMessage);

    File opensslOutputFile = new File(tempDir, "testClearSignMultipleSigners-openssl.eml");

    verifyMessage(file, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

    assertTrue(newMessage.isMimeType("multipart/mixed"));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));

    // the message should contain the signed from, to and subject
    checkForEmbeddedHeaders(newMessage);
}