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:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java

private Multipart getMultipartBody(final Session session) throws MessagingException, IOException {

    // if we have a mimeMessage, use it. Otherwise, build one with what we have
    // We can have both a messageHtml and messageText. Build according to it

    MimeMultipart parentMultipart = new MimeMultipart();
    MimeBodyPart htmlBodyPart = null, textBodyPart = null;

    if (getMimeMessage() != null) {

        // Rebuild a MimeMessage and use this one

        final MimeBodyPart original = new MimeBodyPart();
        final MimeMessage originalMimeMessage = new MimeMessage(session, getMimeMessage().getInputStream());
        final MimeMultipart relatedMultipart = (MimeMultipart) originalMimeMessage.getContent();

        parentMultipart = relatedMultipart;

        htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(relatedMultipart);

    }// w  ww . j  a v a 2  s .  co m

    // The information we have in the mime-message overrides the getMessageHtml.
    if (getMessageHtml() != null && htmlBodyPart != null) {

        final String content = getInputString(getMessageHtml());

        htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(content, "text/html; charset=" + LocaleHelper.getSystemEncoding());
        final MimeMultipart htmlMultipart = new MimeMultipart();
        htmlMultipart.addBodyPart(htmlBodyPart);

        parentMultipart = htmlMultipart;
    }

    if (getMessagePlain() != null) {

        final String content = getInputString(getMessagePlain());

        textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(content, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
        final MimeMultipart textMultipart = new MimeMultipart();
        textMultipart.addBodyPart(textBodyPart);

        parentMultipart = textMultipart;
    }

    // We have both text and html? Encapsulate it in a multipart/alternative

    if (htmlBodyPart != null && textBodyPart != null) {

        final MimeMultipart alternative = new MimeMultipart("alternative");
        alternative.addBodyPart(textBodyPart);
        alternative.addBodyPart(htmlBodyPart);

        parentMultipart = alternative;

    }

    return parentMultipart;

}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

protected void sendMessageAndLog(InternetAddress from, InternetAddress[] to, String subject,
        Map<RecipientType, InternetAddress[]> headerTo, long start, MimeMessage msg, Session session)
        throws MessagingException {
    long preSend = 0;
    if (M_log.isDebugEnabled())
        preSend = System.currentTimeMillis();

    if (allowTransport) {
        msg.saveChanges();//from  ww w.  j  av a 2s .  c  o m

        Transport transport = session.getTransport(protocol);

        if (m_smtpUser != null && m_smtpPassword != null)
            transport.connect(m_smtp, m_smtpUser, m_smtpPassword);
        else
            transport.connect();

        transport.sendMessage(msg, to);

        transport.close();
    }

    long end = 0;
    if (M_log.isDebugEnabled())
        end = System.currentTimeMillis();

    if (M_log.isInfoEnabled()) {
        StringBuilder buf = new StringBuilder();
        buf.append("Email.sendMail: from: ");
        buf.append(from);
        buf.append(" subject: ");
        buf.append(subject);
        buf.append(" to:");
        for (int i = 0; i < to.length; i++) {
            buf.append(" ");
            buf.append(to[i]);
        }
        if (headerTo != null) {
            if (headerTo.containsKey(RecipientType.TO)) {
                buf.append(" headerTo{to}:");
                InternetAddress[] headerToTo = headerTo.get(RecipientType.TO);
                for (int i = 0; i < headerToTo.length; i++) {
                    buf.append(" ");
                    buf.append(headerToTo[i]);
                }
            }
            if (headerTo.containsKey(RecipientType.CC)) {
                buf.append(" headerTo{cc}:");
                InternetAddress[] headerToCc = headerTo.get(RecipientType.CC);
                for (int i = 0; i < headerToCc.length; i++) {
                    buf.append(" ");
                    buf.append(headerToCc[i]);
                }
            }
            if (headerTo.containsKey(RecipientType.BCC)) {
                buf.append(" headerTo{bcc}:");
                InternetAddress[] headerToBcc = headerTo.get(RecipientType.BCC);
                for (int i = 0; i < headerToBcc.length; i++) {
                    buf.append(" ");
                    buf.append(headerToBcc[i]);
                }
            }
        }
        try {
            if (msg.getContent() instanceof Multipart) {
                Multipart parts = (Multipart) msg.getContent();
                buf.append(" with ").append(parts.getCount() - 1).append(" attachments");
            }
        } catch (IOException ioe) {
        }

        if (M_log.isDebugEnabled()) {
            buf.append(" time: ");
            buf.append("" + (end - start));
            buf.append(" in send: ");
            buf.append("" + (end - preSend));
        }

        M_log.info(buf.toString());
    }
}

From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

public void testCommonsEmailOneWaySeparateSessions() {

    Queue emailQueue = null;// ww  w  . j  av a2  s.c  o m
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    Session clientSession = null;
    Session listenerSession = null;
    // it is not necessary to use the Email interface here
    // Email is used here just to allow for multiple types of emails to
    // occupy
    // the same varaible. SimpleEmail etc can each be used directly.
    List<Email> emails = new ArrayList<Email>();
    EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null,
            null, null, null);
    emails.add(new SimpleEmail(messagingService));
    emails.add(new MultiPartEmail(messagingService));
    emails.add(new HtmlEmail(messagingService));
    try {

        listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = listenerSession.createQueue(emailQueueName);

        consumer = listenerSession.createConsumer(emailQueue);

        consumer.setMessageListener(new EmailListener());

        listenerConn.start();

        listenerSession.run();

    } catch (JMSException e2) {
        e2.printStackTrace();
        Assert.assertTrue(false);
    }

    Wiser smtpServer = new Wiser();
    smtpServer.setPort(smtpTestPort);
    smtpServer.start();

    try {
        clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = clientSession.createQueue(emailQueueName);
        producer = clientSession.createProducer(emailQueue);

        clientConn.start();
        clientSession.run();

    } catch (JMSException e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }

    for (Email em : emails) {

        try {
            em.addTo(TEST_EMAIL_TO);
            em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL);
            // host and port will be ignored since the email session is
            // established
            // by
            // the listener
            em.setHostName("localhost");
            em.setSmtpPort(smtpTestPort);
            em.setSubject(TEST_EMAIL_SUBJECT);
            if (em instanceof HtmlEmail) {
                em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL);
            } else if (em instanceof MultiPartEmail) {
                em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL);
            } else if (em instanceof SimpleEmail) {
                em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL);
            }

        } catch (EmailException e1) {
            Assert.assertTrue(false);
            e1.printStackTrace();
        }

        try {
            em.buildMimeMessage();
        } catch (EmailException e1) {
            e1.printStackTrace();
            Assert.assertTrue(false);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {

            em.getMimeMessage().writeTo(os);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

        String content = os.toString();

        ObjectMessage om;
        try {
            om = clientSession.createObjectMessage(content);

            om.setJMSType(emailType);

            LOG.info("Client: Sending test message....");
            producer.send(om);
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

    }

    long start = System.currentTimeMillis();
    while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) {
        // wait for transport
    }
    Assert.assertTrue(listenerMessagesProcessed == 3);

    List<WiserMessage> messages = smtpServer.getMessages();
    Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3);

    for (WiserMessage wisermsg : messages) {
        String body = null;
        String subject = null;
        MimeMessage testmail = null;

        try {
            testmail = wisermsg.getMimeMessage();
        } catch (MessagingException e) {
            Assert.assertTrue(false);
            e.printStackTrace();
        }

        if (testmail != null) {
            LOG.info("SMTP server: test email received: ");
            try {
                LOG.info("To: " + testmail.getHeader("To", ","));

                LOG.info("Subject: " + testmail.getHeader("Subject", ","));
                body = getBodyAsString(testmail.getContent());
                subject = testmail.getHeader("Subject", ",");
            } catch (MessagingException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            } catch (IOException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            }
            LOG.info("Body: " + body);
            Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT));
            Assert.assertTrue(body.contains("This is a Commons"));
        } else {
            Assert.assertTrue(false);
        }
    }

    if (clientSession != null) {
        try {
            clientSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        clientSession = null;
    }

    if (listenerSession != null) {
        try {
            listenerSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        listenerSession = null;
    }

    smtpServer.stop();

}

From source file:org.silverpeas.components.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//from  ww  w.  ja  v a2  s . com
 * @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());
    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:org.silverpeas.core.mail.SmtpMailSendingTest.java

private void assertMailSent(MailToSend verifiedMailToSend, GreenMailOperations mail) throws Exception {
    assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(),
            hasSize(1));/*w w  w  . ja  v a  2s  .c o  m*/

    assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO));

    MimeMessage[] messages = mail.getReceivedMessages();
    assertThat(messages, arrayWithSize(1));

    MimeMessage sentMessage = messages[0];
    MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next();

    assertThat(sentMessage.getFrom().length, is(1));
    assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0];
    assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
    assertThat(internetAddressFrom.getPersonal(),
            is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));

    assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1));
    assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressTo = (InternetAddress) sentMessage
            .getRecipients(Message.RecipientType.TO)[0];
    assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail()));
    assertThat(internetAddressTo.getPersonal(), nullValue());

    assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject()));
    if (verifiedMailToSend.getContent().getValue() instanceof Multipart) {
        assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass()));
    } else {
        assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""),
                is(verifiedMailToSend.getContent().getValue()));
    }

    assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date()));

    assertThat(sentMessage.getReplyTo().length, is(1));
    if (verifiedMailToSend.isReplyToRequired()) {
        assertThat(sentMessage.getHeader("Reply-To"), notNullValue());
        assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class));
        InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0];
        assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
        assertThat(internetAddressReplyTo.getPersonal(),
                is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));
    } else {
        assertThat(sentMessage.getHeader("Reply-To"), nullValue());
        assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString()));
    }
}

From source file:org.silverpeas.core.mail.TestSmtpMailSending.java

private void assertMailSent(MailToSend verifiedMailToSend) throws Exception {
    assertThat("assertMailSent is compatible with one receiver only...", verifiedMailToSend.getTo(),
            hasSize(1));//ww w . j ava  2  s.c  om

    assertThat(verifiedMailToSend.getTo().getRecipientType().getTechnicalType(), is(Message.RecipientType.TO));

    MimeMessage[] messages = greenMailRule.getReceivedMessages();
    assertThat(messages, arrayWithSize(1));

    MimeMessage sentMessage = messages[0];
    MailAddress originalReceiverMailAddress = verifiedMailToSend.getTo().iterator().next();

    assertThat(sentMessage.getFrom().length, is(1));
    assertThat(sentMessage.getFrom()[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressFrom = (InternetAddress) sentMessage.getFrom()[0];
    assertThat(internetAddressFrom.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
    assertThat(internetAddressFrom.getPersonal(),
            is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));

    assertThat(sentMessage.getRecipients(Message.RecipientType.TO).length, is(1));
    assertThat(sentMessage.getRecipients(Message.RecipientType.CC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.BCC), nullValue());
    assertThat(sentMessage.getRecipients(Message.RecipientType.TO)[0], instanceOf(InternetAddress.class));
    InternetAddress internetAddressTo = (InternetAddress) sentMessage
            .getRecipients(Message.RecipientType.TO)[0];
    assertThat(internetAddressTo.getAddress(), is(originalReceiverMailAddress.getEmail()));
    assertThat(internetAddressTo.getPersonal(), nullValue());

    assertThat(sentMessage.getSubject(), is(verifiedMailToSend.getSubject()));
    if (verifiedMailToSend.getContent().getValue() instanceof Multipart) {
        assertThat(sentMessage.getContent(), instanceOf(verifiedMailToSend.getContent().getValue().getClass()));
    } else {
        assertThat(sentMessage.getContent().toString().replaceAll("[\n\r]*$", ""),
                is(verifiedMailToSend.getContent().getValue()));
    }

    assertThat(DateUtils.addSeconds(sentMessage.getSentDate(), 10), greaterThanOrEqualTo(new Date()));

    assertThat(sentMessage.getReplyTo().length, is(1));
    if (verifiedMailToSend.isReplyToRequired()) {
        assertThat(sentMessage.getHeader("Reply-To"), notNullValue());
        assertThat(sentMessage.getReplyTo()[0], instanceOf(InternetAddress.class));
        InternetAddress internetAddressReplyTo = (InternetAddress) sentMessage.getReplyTo()[0];
        assertThat(internetAddressReplyTo.getAddress(), is(verifiedMailToSend.getFrom().getEmail()));
        assertThat(internetAddressReplyTo.getPersonal(),
                is(StringUtil.defaultStringIfNotDefined(verifiedMailToSend.getFrom().getName(), null)));
    } else {
        assertThat(sentMessage.getHeader("Reply-To"), nullValue());
        assertThat(sentMessage.getReplyTo()[0].toString(), is(internetAddressFrom.toString()));
    }
}

From source file:org.sonar.plugins.emailnotifications.EmailNotificationChannelTest.java

@Test
public void shouldSendTestEmail() throws Exception {
    configure();/*from w w  w .j a va 2  s.  c o  m*/
    channel.sendTestEmail("user@nowhere", "Test Message from Sonar", "This is a test message from Sonar.");

    List<WiserMessage> messages = server.getMessages();
    assertThat(messages.size(), is(1));

    MimeMessage email = messages.get(0).getMimeMessage();
    assertThat(email.getHeader("Content-Type", null), is("text/plain; charset=UTF-8"));
    assertThat(email.getHeader("From", ","), is("Sonar <server@nowhere>"));
    assertThat(email.getHeader("To", null), is("<user@nowhere>"));
    assertThat(email.getHeader("Subject", null), is("[SONAR] Test Message from Sonar"));
    assertThat((String) email.getContent(), startsWith("This is a test message from Sonar."));
}

From source file:org.sonar.plugins.emailnotifications.EmailNotificationChannelTest.java

@Test
public void shouldSendThreadedEmail() throws Exception {
    configure();/* w ww.j  a  va  2 s .  c o  m*/
    EmailMessage emailMessage = new EmailMessage().setMessageId("reviews/view/1").setFrom("Full Username")
            .setTo("user@nowhere").setSubject("Review #3").setMessage("I'll take care of this violation.");
    channel.deliver(emailMessage);

    List<WiserMessage> messages = server.getMessages();
    assertThat(messages.size(), is(1));

    MimeMessage email = messages.get(0).getMimeMessage();

    assertThat(email.getHeader("Content-Type", null), is("text/plain; charset=UTF-8"));

    assertThat(email.getHeader("In-Reply-To", null), is("<reviews/view/1@nemo.sonarsource.org>"));
    assertThat(email.getHeader("References", null), is("<reviews/view/1@nemo.sonarsource.org>"));

    assertThat(email.getHeader("List-ID", null), is("Sonar <sonar.nemo.sonarsource.org>"));
    assertThat(email.getHeader("List-Archive", null), is("http://nemo.sonarsource.org"));

    assertThat(email.getHeader("From", ","), is("\"Full Username (Sonar)\" <server@nowhere>"));
    assertThat(email.getHeader("To", null), is("<user@nowhere>"));
    assertThat(email.getHeader("Subject", null), is("[SONAR] Review #3"));
    assertThat((String) email.getContent(), startsWith("I'll take care of this violation."));
}

From source file:org.sonar.plugins.emailnotifications.EmailNotificationChannelTest.java

@Test
public void shouldSendNonThreadedEmail() throws Exception {
    configure();/* w w w  .j a v  a 2s  .c o  m*/
    EmailMessage emailMessage = new EmailMessage().setTo("user@nowhere").setSubject("Foo").setMessage("Bar");
    channel.deliver(emailMessage);

    List<WiserMessage> messages = server.getMessages();
    assertThat(messages.size(), is(1));

    MimeMessage email = messages.get(0).getMimeMessage();

    assertThat(email.getHeader("Content-Type", null), is("text/plain; charset=UTF-8"));

    assertThat(email.getHeader("In-Reply-To", null), nullValue());
    assertThat(email.getHeader("References", null), nullValue());

    assertThat(email.getHeader("List-ID", null), is("Sonar <sonar.nemo.sonarsource.org>"));
    assertThat(email.getHeader("List-Archive", null), is("http://nemo.sonarsource.org"));

    assertThat(email.getHeader("From", null), is("Sonar <server@nowhere>"));
    assertThat(email.getHeader("To", null), is("<user@nowhere>"));
    assertThat(email.getHeader("Subject", null), is("[SONAR] Foo"));
    assertThat((String) email.getContent(), startsWith("Bar"));
}

From source file:org.sonar.server.notification.email.EmailNotificationChannelTest.java

@Test
public void shouldSendTestEmail() throws Exception {
    configure();//w  w  w .j a va2s . co m
    underTest.sendTestEmail("user@nowhere", "Test Message from SonarQube",
            "This is a test message from SonarQube.");

    List<WiserMessage> messages = smtpServer.getMessages();
    assertThat(messages).hasSize(1);

    MimeMessage email = messages.get(0).getMimeMessage();
    assertThat(email.getHeader("Content-Type", null)).isEqualTo("text/plain; charset=UTF-8");
    assertThat(email.getHeader("From", ",")).isEqualTo("SonarQube <server@nowhere>");
    assertThat(email.getHeader("To", null)).isEqualTo("<user@nowhere>");
    assertThat(email.getHeader("Subject", null)).isEqualTo("[SONARQUBE] Test Message from SonarQube");
    assertThat((String) email.getContent()).startsWith("This is a test message from SonarQube.");
}