Example usage for javax.mail.internet MimeMessage getContent

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

Introduction

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

Prototype

@Override
public Object getContent() throws IOException, MessagingException 

Source Link

Document

Return the content as a Java object.

Usage

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

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

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    String template = FileUtils.readFileToString(new File("test/resources/templates/test-user-property.ftl"));

    autoTransactDelegator.setProperty("test@EXAMPLE.com", "notifyTemplate", template);
    autoTransactDelegator.setProperty("test@example.com", "test.user.property.1", "TEST #{test } VALUE");
    autoTransactDelegator.setProperty("test@example.com", "test.user.property.2", "TEST 2");

    Notify mailet = new Notify();

    mailetConfig.setInitParameter("template", "encryption-notification.ftl");
    mailetConfig.setInitParameter("templateProperty", "notifyTemplate");
    mailetConfig.setInitParameter("recipients", "${originator}");
    mailetConfig.setInitParameter("userProperty", "test.user.property.1");
    mailetConfig.setInitParameter("userProperty", "test.user.property.2");

    mailet.init(mailetConfig);/*from  w  ww.  j  av a  2 s  .co 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"));
    recipients.add(new MailAddress("123@example.com"));

    mail.setRecipients(recipients);

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

    mailet.service(mail);

    MailUtils.validateMessage(mail.getMessage());

    assertEquals(1, listener.getSenders().size());
    assertEquals(1, listener.getRecipients().size());
    assertEquals(1, listener.getStates().size());
    assertEquals(1, listener.getMessages().size());
    assertEquals(1, listener.getMails().size());

    assertEquals("[test@example.com]", listener.getRecipients().get(0).toString());

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

    MailUtils.validateMessage(notification);

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

    assertEquals("TEST #{test } VALUE\nTEST 2\nnon existing property not set\n", content);
}

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

private void addEncryptedPDF(MimeMessage message, byte[] pdf) throws MessagingException {
    /*/* w w  w  .j a va2 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.silverpeas.mailinglist.service.job.MailProcessor.java

/**
 * Process an email, extracting attachments and constructing a Message.
 *
 * @param mail the email to be processed.
 * @param mailingList the mailing list it is going to be affected to.
 * @param event the event which will be send at the end of all processing.
 * @throws MessagingException/*  w w  w  .j av  a  2s .  c  om*/
 * @throws IOException
 */
public void prepareMessage(MimeMessage mail, MessageListener mailingList, MessageEvent event)
        throws MessagingException, IOException {
    String sender = ((InternetAddress[]) mail.getFrom())[0].getAddress();
    if (!mailingList.checkSender(sender)) {
        return;
    }
    Message message = new Message();
    message.setComponentId(mailingList.getComponentId());
    message.setSender(sender);
    message.setSentDate(mail.getSentDate());
    message.setMessageId(mail.getMessageID());
    String[] referenceId = mail.getHeader(MAIL_HEADER_IN_REPLY_TO);
    if (referenceId == null || referenceId.length == 0) {
        referenceId = mail.getHeader(MAIL_HEADER_REFERENCES);
    }
    if (referenceId == null || referenceId.length == 0) {
        message.setReferenceId(null);
    } else {
        message.setReferenceId(referenceId[0]);
    }
    message.setTitle(mail.getSubject());
    SilverTrace.info("mailingList", "MailProcessor.prepareMessage()", "mailinglist.notification.error",
            "Processing message " + mail.getSubject());
    Object content = mail.getContent();
    if (content instanceof Multipart) {
        processMultipart((Multipart) content, message);
    } else if (content instanceof String) {
        processBody((String) content, mail.getContentType(), message);
    }
    event.addMessage(message);
}

From source file:com.formkiq.web.WorkflowAddControllerIntegrationTest.java

/**
 * Verify Completion Email.//  w  ww .  j  a v  a  2 s. c  om
 * @throws IOException IOException
 * @throws MessagingException MessagingException
 */
private void verifyCompleteEmail() throws IOException, MessagingException {

    assertEquals(0, getMailSender().getMessages().size());
    assertEquals(1, getMailSender().getMimeMessages().size());

    MimeMessage msg = getMailSender().getMimeMessages().get(0);
    assertEquals("Completed signing Sample WF", msg.getSubject());
    assertEquals("test@formkiq.com", msg.getAllRecipients()[0].toString());

    Multipart multipart = (Multipart) msg.getContent();
    assertEquals(1, multipart.getCount());

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);

    String s = out.toString(CHARSET_UTF8.name());
    assertFalse(s.contains("${sendername}"));
    assertFalse(s.contains("${signername}"));
    assertFalse(s.contains("${doc}"));
    assertFalse(s.contains("${stoken}"));
    assertTrue(s.contains("has reviewed and signed the document"));

    out.close();
}

From source file:com.formkiq.web.WorkflowAddControllerIntegrationTest.java

/**
 * verify email is sent for signing./*from  www.  j a  v  a  2 s.c  o  m*/
 * @return {@link String} The signing URL.
 * @throws IOException IOException
 * @throws MessagingException MessagingException
 */
private String verifyDocsignEmail() throws IOException, MessagingException {

    assertEquals(0, getMailSender().getMessages().size());
    assertEquals(1, getMailSender().getMimeMessages().size());

    MimeMessage msg = getMailSender().getMimeMessages().get(0);
    assertTrue(msg.getSubject().endsWith("sign this"));
    assertTrue(msg.getAllRecipients()[0].toString().endsWith("jacksmith@formkiq.com"));

    Multipart multipart = (Multipart) msg.getContent();
    assertEquals(1, multipart.getCount());

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);

    String s = out.toString(CHARSET_UTF8.name());
    assertTrue(s.contains("John Smith"));
    assertTrue(s.contains("Jack Smith"));
    assertFalse(s.contains("${sendername}"));
    assertFalse(s.contains("${signername}"));
    assertFalse(s.contains("${doc}"));
    assertFalse(s.contains("${stoken}"));
    assertTrue(s.contains("Please review the document and sign at the link above"));

    out.close();

    getMailSender().reset();

    return findHrefUrl(s);
}

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   w w  w.  ja  v  a  2 s  . 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:mitm.application.djigzo.james.mailets.PDFEncryptTest.java

private void checkEncryption(MimeMessage message, String password, boolean hasReplyLink) throws Exception {
    /*//w w  w. ja  v a 2 s . com
     * 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:davmail.imap.ImapConnection.java

protected void appendBodyStructure(StringBuilder buffer, ExchangeSession.Message message) throws IOException {

    buffer.append(" BODYSTRUCTURE ");
    try {//from   w w w.j av  a2s  .co  m
        MimeMessage mimeMessage = message.getMimeMessage();
        Object mimeBody = mimeMessage.getContent();
        if (mimeBody instanceof MimeMultipart) {
            appendBodyStructure(buffer, (MimeMultipart) mimeBody);
        } else {
            // no multipart, single body
            appendBodyStructure(buffer, mimeMessage);
        }
    } catch (UnsupportedEncodingException e) {
        DavGatewayTray.warn(e);
        // failover: send default bodystructure
        buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)");
    } catch (MessagingException me) {
        DavGatewayTray.warn(me);
        // failover: send default bodystructure
        buffer.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL NIL NIL NIL)");
    }
}

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

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

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

    builder.setUseDeprecatedContentTypes(true);

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

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

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

    MimeMessage newMessage = builder.buildMessage();

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

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    SMIMEUtils.dissectSigned((Multipart) newMessage.getContent());

    assertEquals(SMIMEHeader.DEPRECATED_DETACHED_SIGNATURE_TYPE,
            SMIMEUtils.dissectSigned((Multipart) newMessage.getContent())[1].getContentType());

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

    File opensslOutputFile = new File(tempDir, "testClearSignDeprecatedHeaders-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 testClearSignExtraCRLFPreamble() throws Exception {
    MimeMessage message = loadMessage("extra-cr-lf-preamble.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);//from w  w  w  .  j  a v a  2  s.  c o m

    MimeMessage newMessage = builder.buildMessage();

    File file = new File(tempDir, "extra-cr-lf-preamble-signed.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

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

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

    File opensslOutputFile = new File(tempDir, "extra-cr-lf-preamble-openssl.eml");

    verifyMessage(file, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

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

    assertEquals("Martijn Brinkers <martijn@djigzo.com>", newMessage.getHeader("from", ","));
    assertEquals("Martijn Brinkers <martijn@djigzo.com>", newMessage.getHeader("to", ","));
    assertEquals("test multiple attachments extra CR/LF preamble", newMessage.getHeader("subject", ","));

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