Example usage for javax.mail BodyPart isMimeType

List of usage examples for javax.mail BodyPart isMimeType

Introduction

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

Prototype

public boolean isMimeType(String mimeType) throws MessagingException;

Source Link

Document

Is this Part of the specified MIME type?

Usage

From source file:net.fenyo.mail4hotspot.service.MailManager.java

private String getMultipartContentString(final MimeMultipart multipart, final boolean mixed)
        throws IOException, MessagingException {
    // content-type: multipart/mixed ou multipart/alternative

    final StringBuffer selected_content = new StringBuffer();
    for (int i = 0; i < multipart.getCount(); i++) {
        final BodyPart body_part = multipart.getBodyPart(i);
        final Object content = body_part.getContent();

        final String content_string;
        if (String.class.isInstance(content))
            if (body_part.isMimeType("text/html"))
                content_string = GenericTools.html2Text((String) content);
            else if (body_part.isMimeType("text/plain"))
                content_string = (String) content;
            else {
                log.warn("body part content-type not handled: " + body_part.getContentType()
                        + " -> downgrading to String");
                content_string = (String) content;
            }/*from   w  ww  .j  a  v a2  s . c om*/
        else if (MimeMultipart.class.isInstance(content)) {
            boolean part_mixed = false;
            if (body_part.isMimeType("multipart/mixed"))
                part_mixed = true;
            else if (body_part.isMimeType("multipart/alternative"))
                part_mixed = false;
            else {
                log.warn("body part content-type not handled: " + body_part.getContentType()
                        + " -> downgrading to multipart/mixed");
                part_mixed = true;
            }
            content_string = getMultipartContentString((MimeMultipart) content, part_mixed);
        } else {
            log.warn("invalid body part content type and class: " + content.getClass().toString() + " - "
                    + body_part.getContentType());
            content_string = "";
        }

        if (mixed == false) {
            // on slectionne la premire part non vide - ce n'est pas forcment la meilleure alternative, mais comment diffrentiel un text/plain d'une pice jointe d'un text/plain du corps du message, accompagnant un text/html du mme corps ???
            if (selected_content.length() == 0)
                selected_content.append(content_string);
        } else {
            if (selected_content.length() > 0 && content_string.length() > 0)
                selected_content.append("\r\n---\r\n");
            selected_content.append(content_string);
        }
    }
    return selected_content.toString();
}

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   ww  w.j ava 2  s  . 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 {
    /*/*from w  w w .j av  a  2 s  .c om*/
     * 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:com.glaf.mail.business.MailBean.java

/**
 * ?/*  w  w w  .ja  va2s  . c  o  m*/
 * 
 * @param part
 * @throws MessagingException
 * @throws IOException
 */
public void parseAttachment(Part part) throws MessagingException, IOException {
    String filename = "";
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart mpart = mp.getBodyPart(i);
            String dispostion = mpart.getDisposition();
            if ((dispostion != null)
                    && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    logger.debug("filename=" + filename);
                    parseFileContent(filename, mpart.getInputStream());
                }
            } else if (mpart.isMimeType("multipart/*")) {
                parseAttachment(mpart);
            } else {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    parseFileContent(filename, mpart.getInputStream());
                    logger.debug("filename=" + filename);
                }
            }
        }

    } else if (part.isMimeType("message/rfc822")) {
        parseAttachment((Part) part.getContent());
    }
}

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

private void checkEncryption(MimeMessage message, String password, boolean hasReplyLink) throws Exception {
    /*//www.j a va2 s . c o 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: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);//from   www  .  j  a  v  a 2s.c om

    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));
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Extract the attachments present in a mime message
 *
 * @param logger//from  w  ww. j  av  a2  s .  c  om
 * @param content
 * @return A list of body parts of the attachments
 * @throws MessagingException
 * @throws IOException
 */
static public List<BodyPart> extractMessageAttachments(Log logger, Object content)
        throws MessagingException, IOException {
    ArrayList<BodyPart> ret = new ArrayList<BodyPart>();
    if (content instanceof Multipart) {
        Multipart part = (Multipart) content;
        for (int i = 0; i < part.getCount(); i++) {
            BodyPart bodyPart = part.getBodyPart(i);
            String fileName = bodyPart.getFileName();
            String[] contentId = bodyPart.getHeader("Content-ID");
            if (bodyPart.isMimeType("multipart/*")) {
                ret.addAll(extractMessageAttachments(logger, bodyPart.getContent()));
            } else {
                if (contentId != null || fileName != null) {
                    ret.add(bodyPart);
                }
            }
        }
    } else {
        logger.error("Unknown content: " + content.getClass().getName());
    }
    return ret;
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static List<AttachmentInfo> saveAttachmentToWeedFs(Part message, List<AttachmentInfo> attachments,
        EmailRiverConfig config)/*w  w  w  .ja  va 2s  . c  o m*/
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (attachments == null) {
        attachments = new ArrayList<AttachmentInfo>();
    }
    boolean hasAttachment = false;
    try {
        hasAttachment = isContainAttachment(message);
    } catch (MessagingException e) {
        logger.error("save attachment", e);
    } catch (IOException e) {
        logger.error("save attachment", e);
    }
    if (hasAttachment) {

        if (message.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) message.getContent();

            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {

                BodyPart bodyPart = multipart.getBodyPart(i);

                String disp = bodyPart.getDisposition();
                if (disp != null
                        && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();

                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int len = -1;
                    while ((len = bis.read()) != -1) {
                        bos.write(len);
                    }
                    bos.close();
                    bis.close();

                    byte[] data = bos.toByteArray();
                    String fileId = uploadFileToWeedfs(data, config);
                    if (fileId != null) {
                        AttachmentInfo info = new AttachmentInfo();
                        info.fileId = fileId;
                        info.fileName = decodeText(bodyPart.getFileName());
                        info.fileSize = data.length;
                        attachments.add(info);
                    }

                } else if (bodyPart.isMimeType("multipart/*")) {

                    attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));

                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));
                    }
                }
            }
        } else if (message.isMimeType("message/rfc822")) {

            attachments.addAll(saveAttachmentToWeedFs(message, attachments, config));

        }

    }
    return attachments;
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static void saveAttachment(Part part, String destDir)
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();

        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {

            BodyPart bodyPart = multipart.getBodyPart(i);

            String disp = bodyPart.getDisposition();
            if (disp != null
                    && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                InputStream is = bodyPart.getInputStream();
                saveFile(is, destDir, decodeText(bodyPart.getFileName()));
            } else if (bodyPart.isMimeType("multipart/*")) {
                saveAttachment(bodyPart, destDir);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                }/* ww  w  .ja v a  2 s .  c  om*/
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(), destDir);
    }
}

From source file:org.opennms.javamail.JavaReadMailer.java

/**
 * Attempts to reteive the string portion of a message... tries to handle
 * multipart messages as well.  This seems to be working so far with my tests
 * but could use some tweaking later as more types of mail servers are used
 * with this feature.//ww  w  .ja  va2 s .c o m
 *
 * @param msg a {@link javax.mail.Message} object.
 * @return The text portion of an email with each line being an element of the list.
 * @throws javax.mail.MessagingException if any.
 * @throws java.io.IOException if any.
 */
public static List<String> getText(Message msg) throws MessagingException, IOException {

    Object content = null;
    String text = null;

    LOG.debug("getText: getting text of message from MimeType: text/*");

    try {
        text = (String) msg.getContent();

    } catch (ClassCastException cce) {
        content = msg.getContent();

        if (content instanceof MimeMultipart) {

            LOG.debug("getText: content is MimeMultipart, checking for text from each part...");

            for (int cnt = 0; cnt < ((MimeMultipart) content).getCount(); cnt++) {
                BodyPart bp = ((MimeMultipart) content).getBodyPart(cnt);
                if (bp.isMimeType("text/*")) {
                    text = (String) bp.getContent();
                    LOG.debug("getText: found text MIME type: {}", text);
                    break;
                }
            }
            LOG.debug("getText: did not find text within MimeMultipart message.");
        }
    }
    return string2Lines(text);
}