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.common.mail.BodyPartUtils.java

/**
 * Searches for an embedded RFC822 messages. Returns the first embedded RFC822 it finds.
 * Only one level deep is searched./*from   w ww .  j a va2  s .  co m*/
 *  
 * Returns null if there are no embedded message.
 */
public static MimeMessage searchForRFC822(MimeMessage message) throws MessagingException, IOException {
    /*
     * Fast fail. Only multipart mixed messages are supported. 
     */
    if (!message.isMimeType("multipart/mixed")) {
        return null;
    }

    Multipart mp;

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    MimeMessage embeddedMessage = null;

    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (part.isMimeType("message/rfc822")) {
            embeddedMessage = BodyPartUtils.extractFromRFC822(part);

            break;
        }
    }

    return embeddedMessage;
}

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

@Test
public void testEnveloped() throws Exception {
    MimeMessage message = loadMessage("encrypted-validcertificate.eml");

    SMIMEEnvelopedInspector inspector = new SMIMEEnvelopedInspectorImpl(message, keyStoreKeyProvider,
            securityFactory.getNonSensitiveProvider(), securityFactory.getSensitiveProvider());

    MimeMessage decrypted = inspector.getContentAsMimeMessage();

    assertNotNull(decrypted);/*from  ww w.  j  a  v a 2 s  . co m*/
    assertTrue(decrypted.isMimeType("multipart/mixed"));

    checkForEmbeddedHeaders(decrypted);

    File file = new File(tempDir, "test-encrypted-validcertificate-decrypted.eml");

    MailUtils.writeMessage(decrypted, file);
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testLoadMessage() throws FileNotFoundException, MessagingException {
    MimeMessage message = loadMessage("normal-message-with-attach.eml");

    assertTrue(message.isMimeType("multipart/mixed"));
}

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

@Test
public void testOutlook2010MissingSubjKeyIdWorkAround() throws Exception {
    MimeMessage message = loadMessage("outlook2010_cert_missing_subjkeyid.eml");

    KeyStoreKeyProvider keyStoreKeyProvider = new KeyStoreKeyProvider(
            loadKeyStore(new File("test/resources/testdata/keys/outlook2010_cert_missing_subjkeyid.p12"), ""),
            "");/*from   w  w  w  .j  a v a  2  s  .c  o m*/

    keyStoreKeyProvider.setUseOL2010Workaround(true);

    SMIMEEnvelopedInspector inspector = new SMIMEEnvelopedInspectorImpl(message, keyStoreKeyProvider,
            securityFactory.getNonSensitiveProvider(), securityFactory.getSensitiveProvider());

    MimeMessage decrypted = inspector.getContentAsMimeMessage();

    File file = new File(tempDir, "test-testOutlook2010MissingSubjKeyId-decrypted.eml");

    MailUtils.writeMessage(decrypted, file);

    assertNotNull(decrypted);
    assertTrue(decrypted.isMimeType("text/plain"));
    assertNull(decrypted.getSubject());
    assertEquals("Created with Outlook 2010 Beta (14.0.4536.1000)",
            StringUtils.trim((String) decrypted.getContent()));
}

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

@Override
public void internalServiceMail(Mail mail) {
    try {/*from  ww  w  . ja v  a 2s.  c  o  m*/
        MimeMessage sourceMessage = mail.getMessage();

        /*
         * We only need to check application/* mime types because all other, like text cannot 
         * be S/MIME enveloped messages. We won't convert clear signed so we don't have to
         * check multipart messages.
         */
        if (sourceMessage.isMimeType("application/*")) {
            SMIMEType messageType = SMIMEUtils.getSMIMEType(sourceMessage);

            if (messageType == SMIMEType.ENCRYPTED || messageType == SMIMEType.SIGNED) {
                logger.debug("Message is encrypted or opaque signed.");

                createMessageFromTemplate(mail);
            }
        }
    } catch (MissingRecipientsException e) {
        getLogger().warn("MissingRecipientsException. " + ExceptionUtils.getRootCauseMessage(e));

        if (getLogger().isDebugEnabled()) {
            logger.debug("Missing recipients.", e);
        }
    } catch (MessagingException e) {
        getLogger().error("Unhandled exception.", e);
    } catch (PartException e) {
        getLogger().error("Error scanning message.", e);
    } catch (TemplateException e) {
        getLogger().error("Error processing template.", e);
    } catch (IOException e) {
        getLogger().error("Error processing template.", e);
    }
}

From source file:mitm.application.djigzo.relay.RelayHandler.java

private void extractMessageParts(MimeMessage message) throws MessagingException, IOException {
    /*/*from  w  w w  .  j  av  a 2  s.c  o  m*/
     * Fast fail. Only multipart mixed messages are supported. 
     */
    if (!message.isMimeType("multipart/mixed")) {
        return;
    }

    Multipart mp;

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (part.isMimeType("message/rfc822")) {
            relayMessage = BodyPartUtils.extractFromRFC822(part);
        } else if (part.isMimeType("text/xml")) {
            metaPart = part;
        }

        if (metaPart != null && relayMessage != null) {
            break;
        }
    }
}

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

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

    mailetConfig.setInitParameter("algorithm", "AES128");

    SMIMEEncrypt mailet = new SMIMEEncrypt();

    mailet.init(mailetConfig);/*from   w  ww.j a va2s.  c  o  m*/

    Mail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/quoted-printable-multipart.eml"));

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

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

    assertEquals(2, mp.getCount());

    BodyPart part = mp.getBodyPart(0);

    assertTrue(part.isMimeType("text/plain"));
    assertEquals("==", (String) part.getContent());

    mail.setMessage(message);

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

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

    mail.setRecipients(recipients);

    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    mailAttributes.setCertificates(certificates);

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    KeyStoreKeyProvider keyStore = new KeyStoreKeyProvider(
            loadKeyStore(new File("test/resources/testdata/keys/testCertificates.p12"), "test"), "test");

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

    assertEquals(SMIMEType.ENCRYPTED, inspector.getSMIMEType());
    assertEquals(SMIMEEncryptionAlgorithm.AES128_CBC.getOID().toString(),
            inspector.getEnvelopedInspector().getEncryptionAlgorithmOID());
    assertEquals(20, inspector.getEnvelopedInspector().getRecipients().size());

    MimeMessage decrypted = inspector.getContentAsMimeMessage();

    decrypted.saveChanges();

    assertNotNull(decrypted);

    MailUtils.writeMessage(decrypted, new File(tempDir, "testMultipartWithIllegalContentTransferEncoding.eml"));

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

    mp = (MimeMultipart) decrypted.getContent();

    assertEquals(2, mp.getCount());

    part = mp.getBodyPart(0);

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

    /*
     * The body should not be changed to =3D=3D because the body should not be quoted-printable encoded
     * again
     */
    assertEquals("==", (String) part.getContent());
}

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

private void addEncryptedPDF(MimeMessage message, byte[] pdf) throws MessagingException {
    /*// w  ww .  j a  va  2s .  c  o  m
     * Find the existing PDF. The expect that the message is a multipart/mixed. 
     */
    if (!message.isMimeType("multipart/mixed")) {
        throw new MessagingException("Content-type should have been multipart/mixed.");
    }

    Multipart mp;

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    BodyPart pdfPart = null;

    /*
     * Fallback in case the template does not contain a DjigzoHeader.MARKER
     */
    BodyPart fallbackPart = null;

    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) {
            pdfPart = part;

            break;
        }

        /*
         * Fallback scanning for application/pdf in case the template does not contain a DjigzoHeader.MARKER
         */
        if (part.isMimeType("application/pdf")) {
            fallbackPart = part;
        }
    }

    if (pdfPart == null) {
        if (fallbackPart != null) {
            getLogger().info("Marker not found. Using ocet-stream instead.");

            /*
             * Use the octet-stream part
             */
            pdfPart = fallbackPart;
        } else {
            throw new MessagingException("Unable to find the attachment part in the template.");
        }
    }

    pdfPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pdf, "application/pdf")));
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Writes a passed payload data to the passed message object. Could be called from either the MDN
 * processing or the message processing/*  www.  ja  va2  s .c om*/
 */
public void writePayloadsToMessage(byte[] data, AS2Message message, Properties header) throws Exception {
    ByteArrayOutputStream payloadOut = new ByteArrayOutputStream();
    MimeMessage testMessage = new MimeMessage(Session.getInstance(System.getProperties()),
            new ByteArrayInputStream(data));
    //multiple attachments?
    if (testMessage.isMimeType("multipart/*")) {
        this.writePayloadsToMessage(testMessage, message, header);
        return;
    }
    InputStream payloadIn = null;
    AS2Info info = message.getAS2Info();
    if (info instanceof AS2MessageInfo && info.getSignType() == AS2Message.SIGNATURE_NONE
            && ((AS2MessageInfo) info).getCompressionType() == AS2Message.COMPRESSION_NONE) {
        payloadIn = new ByteArrayInputStream(data);
    } else if (testMessage.getSize() > 0) {
        payloadIn = testMessage.getInputStream();
    } else {
        payloadIn = new ByteArrayInputStream(data);
    }
    this.copyStreams(payloadIn, payloadOut);
    payloadOut.flush();
    payloadOut.close();
    byte[] payloadData = payloadOut.toByteArray();
    AS2Payload as2Payload = new AS2Payload();
    as2Payload.setData(payloadData);
    String contentIdHeader = header.getProperty("content-id");
    if (contentIdHeader != null) {
        as2Payload.setContentId(contentIdHeader);
    }
    String contentTypeHeader = header.getProperty("content-type");
    if (contentTypeHeader != null) {
        as2Payload.setContentType(contentTypeHeader);
    }
    try {
        as2Payload.setOriginalFilename(testMessage.getFileName());
    } catch (MessagingException e) {
        if (this.logger != null) {
            this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                    new Object[] { info.getMessageId(), e.getMessage(), }), info);
        }
    }
    if (as2Payload.getOriginalFilename() == null) {
        String filenameHeader = header.getProperty("content-disposition");
        if (filenameHeader != null) {
            //test part for convinience: extract file name
            MimeBodyPart filenamePart = new MimeBodyPart();
            filenamePart.setHeader("content-disposition", filenameHeader);
            try {
                as2Payload.setOriginalFilename(filenamePart.getFileName());
            } catch (MessagingException e) {
                if (this.logger != null) {
                    this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                            new Object[] { info.getMessageId(), e.getMessage(), }), info);
                }
            }
        }
    }
    message.addPayload(as2Payload);
}

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

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

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    PDFEncrypt mailet = new PDFEncrypt();

    mailetConfig.setInitParameter("template", "encrypted-pdf.ftl");
    mailetConfig.setInitParameter("encryptedProcessor", "encryptedProcessor");
    mailetConfig.setInitParameter("notEncryptedProcessor", "notEncryptedProcessor");
    mailetConfig.setInitParameter("passwordMode", "single");
    mailetConfig.setInitParameter("passThrough", "false");

    mailet.init(mailetConfig);//  w  w w .  ja v a2  s .c o  m

    MockMail mail = new MockMail();

    MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/normal-message-with-attach.eml"));

    message.setFrom(new InternetAddress("test@example.com", "=?UTF-8?B?w6TDtsO8IMOEw5bDnA==?="));

    mail.setMessage(message);

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

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

    mail.setRecipients(recipients);

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

    // password is test when encrypted with password 'djigzo'
    new DjigzoMailAttributesImpl(mail).setEncryptedPassword(Base64.decodeBase64(MiscStringUtils
            .toAsciiBytes("lklfx6SWxIkAAAAQ1VTbMJjznNZjVvdggckSPQAACAAAAAAQKAxcw630UmyVhyZPiW9xhg==")));

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    TestUtils.saveMessages(tempDir, "testEncryptPDFFromPersonalUTF8", listener.getMessages());

    assertEquals(1, listener.getMessages().size());
    assertEquals("encryptedProcessor", listener.getStates().get(0));
    assertEquals(2, listener.getRecipients().get(0).size());
    assertTrue(listener.getRecipients().get(0).contains(new MailAddress("123@example.com")));
    assertTrue(listener.getRecipients().get(0).contains(new MailAddress("m.brinkers@pobox.com")));
    assertEquals("sender@example.com", listener.getSenders().get(0).toString());
    assertEquals(Mail.GHOST, mail.getState());
    assertNotNull(listener.getMessages().get(0));
    assertTrue(message != listener.getMessages().get(0));

    MimeMessage encrypted = listener.getMessages().get(0);

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

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

    assertEquals(2, mp.getCount());

    BodyPart messagePart = mp.getBodyPart(0);
    BodyPart pdfPart = mp.getBodyPart(1);

    assertTrue(messagePart.isMimeType("text/plain"));
    assertTrue(pdfPart.isMimeType("application/pdf"));

    // check if the body contains   (which is the decoded from personal name)
    String text = (String) messagePart.getContent();

    assertTrue(text.contains(" "));

    MailUtils.validateMessage(listener.getMessages().get(0));
}