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.ikasan.component.endpoint.email.producer.EmailProducerTest.java

@Test
public void test_successful_email_withAttachment() throws MessagingException, IOException {

    EmailProducerConfiguration emailProducerConfiguration = getConfiguration(true, null);

    EmailProducer emailProducer = new EmailProducer();
    ((Configured) emailProducer).setConfiguration(emailProducerConfiguration);
    ((ManagedResource) emailProducer).startManagedResource();

    emailProducer.invoke(getEmailPayload(true, null));
    List<WiserMessage> messages = wiser.getMessages();

    Assert.assertTrue("Should be three messages - one per addressee", messages.size() == 3);
    for (WiserMessage message : wiser.getMessages()) {
        Assert.assertTrue("sender should be " + sender, sender.equals(message.getEnvelopeSender()));

        MimeMessage mimeMessage = message.getMimeMessage();
        MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
        Assert.assertTrue("should be 2 bodypart", mimeMultipart.getCount() == 2);
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        String content = (String) bodyPart.getContent();
        Assert.assertTrue("The email content should be empty", content.isEmpty());
        BodyPart attachment = mimeMultipart.getBodyPart(1);
        Assert.assertEquals("Check attachment file name", "testAttachment", attachment.getFileName());
        Assert.assertTrue("Check file content",
                IOUtils.toString(attachment.getDataHandler().getDataSource().getInputStream())
                        .contains("1997,Ford,E350"));
        Assert.assertTrue("Should find email format as \"text/plain\"",
                bodyPart.getContentType().contains("text/plain"));

    }//from w ww  . j a  v  a2 s  .  c o  m
}

From source file:org.jtalks.tests.jcommune.mail.mailtrap.MailtrapMail.java

private String tryToGetLink(String recipient) {
    Gson gson = new Gson();
    MessageDto[] messages;/*ww w  .j  a v  a2s. co  m*/
    String link = null;

    messages = gson.fromJson(MailtrapClient.getMessages(), MessageDto[].class);

    List<Metadata> metadataList = getMetadataList(messages);

    String id = NOT_FOUND_ID;
    DateTime createdAt = null;
    for (Metadata metadata : metadataList) {
        if (!recipient.equals(metadata.getRecipient())) {
            continue;
        }
        if (id.equals(NOT_FOUND_ID) || metadata.getDateTime().isAfter(createdAt)) {
            id = metadata.getId();
        }
    }
    if (id.equals(NOT_FOUND_ID)) {
        return link;
    }

    MessageDto messageDto = gson.fromJson(MailtrapClient.getMessage(id), MessageDto.class);

    try {
        String source = messageDto.getMessage().getSource();

        MimeMessage message = new MimeMessage(Session.getInstance(new Properties()),
                (new ByteArrayInputStream(source.getBytes())));
        Multipart multipart = (Multipart) message.getContent();
        Multipart multipart1 = (Multipart) multipart.getBodyPart(0).getContent();
        Multipart multipart2 = (Multipart) multipart1.getBodyPart(0).getContent();
        String escapedText = (String) multipart2.getBodyPart(0).getContent();
        String text = StringEscapeUtils.unescapeHtml(escapedText);
        Matcher matcher = Pattern.compile("(http://.*/activate/.*)[\\s]").matcher(text);
        if (matcher.find()) {
            link = matcher.group(1);
        }
    } catch (MessagingException | IOException e) {
        LOGGER.warn("Problem occurred while grabbing activation link from Mailtrap", e);
    }
    return link;
}

From source file:org.masukomi.aspirin.core.Bouncer.java

/**
 * This generates a response to the Return-Path address, or the address of
 * the message's sender if the Return-Path is not available. Note that this
 * is different than a mail-client's reply, which would use the Reply-To or
 * From header.//from w  w w.ja va 2 s .co m
 * 
 * @param mail
 *            DOCUMENT ME!
 * @param message
 *            DOCUMENT ME!
 * @param bouncer
 *            DOCUMENT ME!
 * 
 * @throws MessagingException
 *             DOCUMENT ME!
 */
static public void bounce(MailQue que, Mail mail, String message, MailAddress bouncer)
        throws MessagingException {
    if (bouncer != null) {
        if (log.isDebugEnabled()) {
            log.debug("bouncing message to postmaster");
        }
        MimeMessage orig = mail.getMessage();
        //Create the reply message
        MimeMessage reply = (MimeMessage) orig.reply(false);
        //If there is a Return-Path header,
        if (orig.getHeader(RFC2822Headers.RETURN_PATH) != null) {
            //Return the message to that address, not to the Reply-To
            // address
            reply.setRecipient(MimeMessage.RecipientType.TO,
                    new InternetAddress(orig.getHeader(RFC2822Headers.RETURN_PATH)[0]));
        }
        //Create the list of recipients in our MailAddress format
        Collection recipients = new HashSet();
        Address[] addresses = reply.getAllRecipients();
        for (int i = 0; i < addresses.length; i++) {
            recipients.add(new MailAddress((InternetAddress) addresses[i]));
        }
        //Change the sender...
        reply.setFrom(bouncer.toInternetAddress());
        try {
            //Create the message body
            MimeMultipart multipart = new MimeMultipart();
            //Add message as the first mime body part
            MimeBodyPart part = new MimeBodyPart();
            part.setContent(message, "text/plain");
            part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
            multipart.addBodyPart(part);
            //Add the original message as the second mime body part
            part = new MimeBodyPart();
            part.setContent(orig.getContent(), orig.getContentType());
            part.setHeader(RFC2822Headers.CONTENT_TYPE, orig.getContentType());
            multipart.addBodyPart(part);
            reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
            reply.setContent(multipart);
            reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
        } catch (IOException ioe) {
            throw new MessagingException("Unable to create multipart body", ioe);
        }
        //Send it off...
        //sendMail( bouncer, recipients, reply );
        que.queMail(reply);
    }
}

From source file:org.mobicents.servlet.restcomm.email.EmailServiceTest.java

@Test
public void testSendEmail() {
    new JavaTestKit(system) {
        {/*from   ww w  .j  a v a 2 s  .c o m*/
            final ActorRef observer = getRef();

            // Send the email.
            final Mail emailMsg = new Mail("hascode@localhost", "someone@localhost.com",
                    "Testing Email Service", "This is the subject of the email service testing",
                    "someone2@localhost.com, test@localhost.com, test3@localhost.com",
                    "someone3@localhost.com, test2@localhost.com");
            emailService.tell(new EmailRequest(emailMsg), observer);

            final EmailResponse response = expectMsgClass(FiniteDuration.create(60, TimeUnit.SECONDS),
                    EmailResponse.class);
            assertTrue(response.succeeded());

            // fetch messages from server
            MimeMessage[] messages = mailServer.getReceivedMessages();
            assertNotNull(messages);
            assertEquals(6, messages.length);
            MimeMessage m = messages[0];
            try {
                assertEquals(emailMsg.subject(), m.getSubject());
                assertTrue(String.valueOf(m.getContent()).contains(emailMsg.body()));
                assertEquals(emailMsg.from(), m.getFrom()[0].toString());
            } catch (Exception e) {
                assertTrue(false);
            }
        }
    };
}

From source file:org.nuxeo.ecm.platform.mail.action.TransformMessageAction.java

private void processMimeMessage(MimeMessage message) throws MessagingException, IOException {
    Object object = message.getContent();
    if (object instanceof String) {
        addToTextMessage(message.getContent().toString(), true);
    } else if (object instanceof MimeMultipart) {
        processMultipartMessage((MimeMultipart) object);
        processSavedTextMessageBody();/*from  w  w w . j a  v a2  s.  com*/
    }
}

From source file:org.obm.sync.server.mailer.EventChangeMailerTest.java

protected InvitationParts checkNotificationStructure(MimeMessage mimeMessage)
        throws UnsupportedEncodingException, IOException, MessagingException {
    InvitationParts parts = new InvitationParts();
    parts.rawMessage = getRawMessage(mimeMessage);
    assertThat(mimeMessage.getContentType()).startsWith("multipart/alternative");
    assertThat(mimeMessage.getContent()).isInstanceOf(Multipart.class);
    Multipart alternative = (Multipart) mimeMessage.getContent();
    assertThat(alternative.getCount()).isEqualTo(2);
    parts.plainText = alternative.getBodyPart(0);
    assertThat(parts.plainText.getContentType()).startsWith("text/plain; charset=UTF-8");
    parts.htmlText = alternative.getBodyPart(1);
    assertThat(parts.htmlText.getContentType()).startsWith("text/html; charset=UTF-8");
    return parts;
}

From source file:org.obm.sync.server.mailer.EventChangeMailerTest.java

private InvitationParts checkInvitationStructure(MimeMessage mimeMessage)
        throws UnsupportedEncodingException, IOException, MessagingException {
    InvitationParts parts = new InvitationParts();
    parts.rawMessage = getRawMessage(mimeMessage);
    assertThat(mimeMessage.getContentType()).startsWith("multipart/mixed");
    assertThat(mimeMessage.getContent()).isInstanceOf(Multipart.class);
    Multipart mixed = (Multipart) mimeMessage.getContent();
    assertThat(mixed.getCount()).isEqualTo(2);
    BodyPart firstPart = mixed.getBodyPart(0);
    assertThat(firstPart.getContentType()).startsWith("multipart/alternative");
    assertThat(firstPart.getContent()).isInstanceOf(Multipart.class);
    Multipart alternative = (Multipart) firstPart.getContent();
    assertThat(alternative.getCount()).isEqualTo(3);
    parts.plainText = alternative.getBodyPart(0);
    assertThat(parts.plainText.getContentType()).startsWith("text/plain; charset=UTF-8");
    parts.htmlText = alternative.getBodyPart(1);
    assertThat(parts.htmlText.getContentType()).startsWith("text/html; charset=UTF-8");
    parts.textCalendar = alternative.getBodyPart(2);
    parts.applicationIcs = mixed.getBodyPart(1);
    assertThat(parts.applicationIcs.getContentType()).isEqualTo("application/ics; name=meeting.ics");
    return parts;
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

@Override
public void sendMessage(MimeMessage msg, MailerResult result) {
    try {/*w ww.  j a v  a 2 s. c o  m*/
        if (Settings.isJUnitTest()) {
            //we want not send really e-mails
        } else if (mailModule.isMailHostEnabled() && result.getReturnCode() == MailerResult.OK) {
            // now send the mail
            if (Settings.isDebuging()) {
                try {
                    logInfo("E-mail send: " + msg.getSubject());
                    logInfo("Content    : " + msg.getContent());
                } catch (IOException e) {
                    logError("", e);
                }
            }
            Transport.send(msg);
        } else if (Settings.isDebuging() && result.getReturnCode() == MailerResult.OK) {
            try {
                logInfo("E-mail send: " + msg.getSubject());
                logInfo("Content    : " + msg.getContent());
            } catch (IOException e) {
                logError("", e);
            }
        } else {
            result.setReturnCode(MailerResult.MAILHOST_UNDEFINED);
        }
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        logWarn("Could not send mail", e);
    }
}

From source file:org.opens.emailsender.EmailSender.java

/**
 *
 * @param emailFrom//from w w  w. j a  va 2  s  . c  o m
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.error("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.error("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn(ex.getMessage());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn(e.getMessage());
    } catch (MessagingException e) {
        LOGGER.warn(e.getMessage());
    }
}

From source file:org.pentaho.platform.util.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {// w  ww  . ja  v  a  2s  .co  m
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        final MimeMessage msg;

        if (EMBEDDED_HTML.equals(attachmentMimeType)) {

            //Message is ready
            msg = new MimeMessage(session, attachment);

            if (body != null) {
                //We need to add message to the top of the email body
                final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent();
                final MimeMultipart newMultipart = new MimeMultipart("related");

                for (int i = 0; i < oldMultipart.getCount(); i++) {
                    BodyPart bodyPart = oldMultipart.getBodyPart(i);

                    final Object content = bodyPart.getContent();
                    //Main HTML body
                    if (content instanceof String) {
                        final String newContent = body + "<br/><br/>" + content;
                        final MimeBodyPart part = new MimeBodyPart();
                        part.setText(newContent, "UTF-8", "html");
                        newMultipart.addBodyPart(part);
                    } else {
                        //CID attachments
                        newMultipart.addBodyPart(bodyPart);
                    }
                }

                msg.setContent(newMultipart);
            }
        } else {

            // construct the message
            msg = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            if (attachment == null) {
                logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
                return false;
            }

            ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

            if (body != null) {
                MimeBodyPart bodyMessagePart = new MimeBodyPart();
                bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(bodyMessagePart);
            }

            // attach the file to the message
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
            multipart.addBodyPart(attachmentBodyPart);

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}