Java Code Examples for javax.mail.internet.MimeBodyPart#getContentType()

The following examples show how to use javax.mail.internet.MimeBodyPart#getContentType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public boolean isEncrypted(MimeBodyPart part) throws MessagingException {
    ContentType contentType = new ContentType(part.getContentType());
    String baseType = contentType.getBaseType().toLowerCase();

    if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
        String smimeType = contentType.getParameter("smime-type");
        boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("enveloped-data");
        if (!checkResult && logger.isDebugEnabled()) {
            logger.debug("Check for encrypted data failed on SMIME content type: " + smimeType);
        }
        return (checkResult);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Check for encrypted data failed on BASE content type: " + baseType);
    }
    return false;
}
 
Example 2
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public boolean isCompressed(MimeBodyPart part) throws MessagingException {
    ContentType contentType = new ContentType(part.getContentType());
    String baseType = contentType.getBaseType().toLowerCase();

    if (logger.isTraceEnabled()) {
        try {
            logger.trace("Compression check.  MIME Base Content-Type:" + contentType.getBaseType());
            logger.trace("Compression check.  SMIME-TYPE:" + contentType.getParameter("smime-type"));
            logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Disposition:" + part.getDisposition());
        } catch (MessagingException e) {
            logger.trace("Compression check: no data available.");
        }
    }
    if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
        String smimeType = contentType.getParameter("smime-type");
        boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("compressed-data");
        if (!checkResult && logger.isDebugEnabled()) {
            logger.debug("Check for compressed data failed on SMIME content type: " + smimeType);
        }
        return (checkResult);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Check for compressed data failed on BASE content type: " + baseType);
    }
    return false;
}
 
Example 3
Source File: EmailerTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
private void doTestTextAttachment(boolean useFs) throws IOException, MessagingException {
    emailerConfig.setFileStorageUsed(useFs);
    testMailSender.clearBuffer();

    String attachmentText = "Test Attachment Text";
    EmailAttachment textAttach = EmailAttachment.createTextAttachment(attachmentText, "ISO-8859-1", "test.txt");

    EmailInfo myInfo = EmailInfoBuilder.create()
            .setAddresses("[email protected]")
            .setCaption("Test")
            .setBody("Test")
            .setAttachments(textAttach)
            .build();
    emailer.sendEmailAsync(myInfo);

    emailer.processQueuedEmails();

    MimeMessage msg = testMailSender.fetchSentEmail();
    MimeBodyPart firstAttachment = getFirstAttachment(msg);

    // check content bytes
    Object content = firstAttachment.getContent();
    assertTrue(content instanceof InputStream);
    byte[] data = IOUtils.toByteArray((InputStream) content);
    assertEquals(attachmentText, new String(data, "ISO-8859-1"));

    // disposition
    assertEquals(Part.ATTACHMENT, firstAttachment.getDisposition());

    // charset header
    String contentType = firstAttachment.getContentType();
    assertTrue(contentType.toLowerCase().contains("charset=iso-8859-1"));
}
 
Example 4
Source File: EmailerTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
private void doTestInlineImage(boolean useFs) throws IOException, MessagingException {
    emailerConfig.setFileStorageUsed(useFs);
    testMailSender.clearBuffer();

    byte[] imageBytes = new byte[]{1, 2, 3, 4, 5};
    String fileName = "logo.png";
    EmailAttachment imageAttach = new EmailAttachment(imageBytes, fileName, "logo");

    EmailInfo myInfo = EmailInfoBuilder.create()
            .setAddresses("[email protected]")
            .setCaption("Test")
            .setBody("Test")
            .setAttachments(imageAttach)
            .build();
    emailer.sendEmailAsync(myInfo);

    emailer.processQueuedEmails();

    MimeMessage msg = testMailSender.fetchSentEmail();
    MimeBodyPart attachment = getInlineAttachment(msg);

    // check content bytes
    InputStream content = (InputStream) attachment.getContent();
    byte[] data = IOUtils.toByteArray(content);
    assertByteArrayEquals(imageBytes, data);

    // disposition
    assertEquals(Part.INLINE, attachment.getDisposition());

    // mime type
    String contentType = attachment.getContentType();
    assertTrue(contentType.contains("image/png"));
}
 
Example 5
Source File: EmailerTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
private void doTestPdfAttachment(boolean useFs) throws IOException, MessagingException {
    emailerConfig.setFileStorageUsed(useFs);
    testMailSender.clearBuffer();

    byte[] pdfBytes = new byte[]{1, 2, 3, 4, 6};
    String fileName = "invoice.pdf";
    EmailAttachment pdfAttach = new EmailAttachment(pdfBytes, fileName);

    EmailInfo myInfo = EmailInfoBuilder.create()
            .setAddresses("[email protected]")
            .setCaption("Test")
            .setBody("Test")
            .setAttachments(pdfAttach)
            .build();
    emailer.sendEmailAsync(myInfo);

    emailer.processQueuedEmails();

    MimeMessage msg = testMailSender.fetchSentEmail();
    MimeBodyPart attachment = getFirstAttachment(msg);

    // check content bytes
    InputStream content = (InputStream) attachment.getContent();
    byte[] data = IOUtils.toByteArray(content);
    assertByteArrayEquals(pdfBytes, data);

    // disposition
    assertEquals(Part.ATTACHMENT, attachment.getDisposition());

    // mime type
    String contentType = attachment.getContentType();
    assertTrue(contentType.contains("application/pdf"));
}
 
Example 6
Source File: BaseMessage.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public DataHistoryItem setData(MimeBodyPart data) throws OpenAS2Exception {
    try {
        DataHistoryItem historyItem = new DataHistoryItem(data.getContentType());
        setData(data, historyItem);

        return historyItem;
    } catch (Exception e) {
        throw new WrappedException(e);
    }
}
 
Example 7
Source File: EmailerTest.java    From cuba with Apache License 2.0 4 votes vote down vote up
private String getBodyContentType(MimeMessage msg) throws Exception {
    MimeBodyPart textPart = getTextPart(msg);
    return textPart.getContentType();
}
 
Example 8
Source File: AS2ReceiverHandler.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void createMDNData(Session session, MessageMDN mdn, String micAlg, String signatureProtocol) throws Exception {
    // Create the report and sub-body parts
    MimeMultipart reportParts = new MimeMultipart();

    // Create the text part
    MimeBodyPart textPart = new MimeBodyPart();
    String text = mdn.getText() + "\r\n";
    textPart.setContent(text, "text/plain");
    textPart.setHeader("Content-Type", "text/plain");
    reportParts.addBodyPart(textPart);

    // Create the report part
    MimeBodyPart reportPart = new MimeBodyPart();
    InternetHeaders reportValues = new InternetHeaders();
    reportValues.setHeader("Reporting-UA", mdn.getAttribute(AS2MessageMDN.MDNA_REPORTING_UA));
    reportValues.setHeader("Original-Recipient", mdn.getAttribute(AS2MessageMDN.MDNA_ORIG_RECIPIENT));
    reportValues.setHeader("Final-Recipient", mdn.getAttribute(AS2MessageMDN.MDNA_FINAL_RECIPIENT));
    reportValues.setHeader("Original-Message-ID", mdn.getAttribute(AS2MessageMDN.MDNA_ORIG_MESSAGEID));
    reportValues.setHeader("Disposition", mdn.getAttribute(AS2MessageMDN.MDNA_DISPOSITION));
    reportValues.setHeader("Received-Content-MIC", mdn.getAttribute(AS2MessageMDN.MDNA_MIC));

    Enumeration<String> reportEn = reportValues.getAllHeaderLines();
    StringBuffer reportData = new StringBuffer();

    while (reportEn.hasMoreElements()) {
        reportData.append(reportEn.nextElement()).append("\r\n");
    }

    reportData.append("\r\n");

    String reportText = reportData.toString();
    reportPart.setContent(reportText, AS2Standards.DISPOSITION_TYPE);
    reportPart.setHeader("Content-Type", AS2Standards.DISPOSITION_TYPE);
    reportParts.addBodyPart(reportPart);

    // Convert report parts to MimeBodyPart
    MimeBodyPart report = new MimeBodyPart();
    reportParts.setSubType(AS2Standards.REPORT_SUBTYPE);
    report.setContent(reportParts);
    String contentType = reportParts.getContentType();
    if ("true".equalsIgnoreCase(Properties.getProperty("remove_multipart_content_type_header_folding", "false"))) {
        contentType = contentType.replaceAll("\r\n[ \t]*", " ");
    }
    report.setHeader("Content-Type", contentType);

    // Sign the data if needed
    if (signatureProtocol != null) {
        CertificateFactory certFx = session.getCertificateFactory();

        try {
            // The receiver of the original message is the sender of the MDN....
            X509Certificate senderCert = certFx.getCertificate(mdn, Partnership.PTYPE_RECEIVER);
            PrivateKey senderKey = certFx.getPrivateKey(mdn, senderCert);
            Partnership p = mdn.getPartnership();
            String contentTxfrEncoding = p.getAttribute(Partnership.PA_CONTENT_TRANSFER_ENCODING);
            boolean isRemoveCmsAlgorithmProtectionAttr = "true".equalsIgnoreCase(p.getAttribute(Partnership.PA_REMOVE_PROTECTION_ATTRIB));
            if (contentTxfrEncoding == null) {
                contentTxfrEncoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
            }
            // sign the data using CryptoHelper
            MimeBodyPart signedReport = AS2Util.getCryptoHelper().sign(report, senderCert, senderKey, micAlg, contentTxfrEncoding, false, isRemoveCmsAlgorithmProtectionAttr);
            mdn.setData(signedReport);
        } catch (CertificateNotFoundException cnfe) {
            cnfe.terminate();
            mdn.setData(report);
        } catch (KeyNotFoundException knfe) {
            knfe.terminate();
            mdn.setData(report);
        }
    } else {
        mdn.setData(report);
    }

    // Update the MDN headers with content information
    MimeBodyPart data = mdn.getData();
    String headerContentType = data.getContentType();
    if ("true".equalsIgnoreCase(Properties.getProperty("remove_http_header_folding", "true"))) {
        headerContentType = headerContentType.replaceAll("\r\n[ \t]*", " ");
    }
    mdn.setHeader("Content-Type", headerContentType);

    // int size = getSize(data);
    // mdn.setHeader("Content-Length", Integer.toString(size));
}
 
Example 9
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public boolean isSigned(MimeBodyPart part) throws MessagingException {
    ContentType contentType = new ContentType(part.getContentType());
    String baseType = contentType.getBaseType().toLowerCase();

    return baseType.equalsIgnoreCase("multipart/signed");
}