Example usage for javax.mail.internet MimeMessage setSubject

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

Introduction

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

Prototype

@Override
public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the "Subject" header field.

Usage

From source file:org.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java

public void prepare(MimeMessage message) throws Exception {

    message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
        message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }// w  w  w  .  j  a  v  a2s  . c o m

    if (getFrom() != null) {
        List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
        toAddress.add(new InternetAddress(getFrom(), getFromName()));
        message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getBcc() != null) {
        message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(getBcc()));
    }
    if (getSubject() != null) {
        message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
        textBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        textBodyPart.setContent(getPlainTextContent(), "text/plain; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
        htmlBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        htmlBodyPart.setContent(getHtmlContent(), "text/html; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

From source file:org.overlord.sramp.governance.services.NotificationResource.java

/**
 * POST to email a notification about an artifact.
 *
 * @param environment/*from  w w w .  ja v a 2 s  .co  m*/
 * @param uuid
 * @throws SrampAtomException
 */
@POST
@Path("email/{group}/{template}/{target}/{uuid}")
@Produces("application/xml")
public Map<String, ValueEntity> emailNotification(@Context HttpServletRequest request,
        @PathParam("group") String group, @PathParam("template") String template,
        @PathParam("target") String target, @PathParam("uuid") String uuid) throws Exception {

    Map<String, ValueEntity> results = new HashMap<String, ValueEntity>();
    try {
        // 0. run the decoder on the arguments, after replacing * by % (this so parameters can
        //    contain slashes (%2F)
        group = SlashDecoder.decode(group);
        template = SlashDecoder.decode(template);
        target = SlashDecoder.decode(target);
        uuid = SlashDecoder.decode(uuid);

        // 1. get the artifact from the repo
        SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
        QueryResultSet queryResultSet = client.buildQuery("/s-ramp[@uuid = ?]").parameter(uuid).query(); //$NON-NLS-1$
        if (queryResultSet.size() == 0) {
            results.put(GovernanceConstants.STATUS, new ValueEntity("fail")); //$NON-NLS-1$
            results.put(GovernanceConstants.MESSAGE,
                    new ValueEntity("Could not obtain artifact from repository.")); //$NON-NLS-1$
            return results;
        }
        ArtifactSummary artifactSummary = queryResultSet.iterator().next();

        // 2. get the destinations for this group
        NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$
        if (destinations == null) {
            destinations = new NotificationDestinations(group, governance.getDefaultEmailFromAddress(),
                    group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$
        }

        // 3. send the email notification
        try {
            MimeMessage m = new MimeMessage(mailSession);
            Address from = new InternetAddress(destinations.getFromAddress());
            Address[] to = new InternetAddress[destinations.getToAddresses().length];
            for (int i = 0; i < destinations.getToAddresses().length; i++) {
                to[i] = new InternetAddress(destinations.getToAddresses()[i]);
            }
            m.setFrom(from);
            m.setRecipients(Message.RecipientType.TO, to);

            String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL subjectUrl = Governance.class.getClassLoader().getResource(subject);
            if (subjectUrl != null)
                subject = IOUtils.toString(subjectUrl);
            subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            m.setSubject(subject);

            m.setSentDate(new java.util.Date());
            String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
            URL contentUrl = Governance.class.getClassLoader().getResource(content);
            if (contentUrl != null)
                content = IOUtils.toString(contentUrl);
            content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
            content = content.replaceAll("\\$\\{dtgovurl}", governance.getDTGovUiUrl()); //$NON-NLS-1$
            m.setContent(content, "text/plain"); //$NON-NLS-1$
            Transport.send(m);
        } catch (javax.mail.MessagingException e) {
            logger.error(e.getMessage(), e);
        }

        // 4. build the response
        results.put(GovernanceConstants.STATUS, new ValueEntity("success")); //$NON-NLS-1$

        return results;
    } catch (Exception e) {
        logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$
        throw new SrampAtomException(e);
    }
}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifyAccountDeleted(TemporaryMailContainer container) {
    try {/*  w  w w.j a  v  a2s . c o m*/
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s

        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s,<br><br>Your account has been deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted.subject"));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:org.opencastproject.messages.MailService.java

/** Message -> MimeMessage. */
private MimeMessage toMimeMessage(Mail mail) throws Exception {
    final MimeMessage msg = smtpService.createMessage();
    for (EmailAddress reply : mail.getReplyTo())
        msg.setReplyTo(new Address[] { new InternetAddress(reply.getAddress(), reply.getName(), "UTF-8") });

    // recipient//from   w w  w. j a v  a 2s  . c o  m
    for (EmailAddress recipient : mail.getRecipients()) {
        msg.addRecipient(javax.mail.Message.RecipientType.TO,
                new InternetAddress(recipient.getAddress(), recipient.getName(), "UTF-8"));
    }

    // subject
    msg.setSubject(mail.getSubject());

    EmailAddress from = mail.getSender();
    msg.setFrom(new InternetAddress(from.getAddress(), from.getName(), "UTF-8"));
    // body
    msg.setText(mail.getBody(), "UTF-8");
    return msg;
}

From source file:it.infn.ct.chipster.Chipster.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String user_emailAddress, String credential, String chipster_HOST) {

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- User's email = " + user_emailAddress);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);
    properties.setProperty("mail.debug", "true");

    //properties.setProperty("mail.smtp.auth", "false");        

    // Get the default Session object.
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    try {/*from  w  ww . j  a v  a 2  s.  c  o m*/
        // Create a default MimeMessage object.
        javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new javax.mail.internet.InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(javax.mail.Message.RecipientType.TO, new javax.mail.internet.InternetAddress(TO));
        message.addRecipient(javax.mail.Message.RecipientType.CC,
                new javax.mail.internet.InternetAddress(user_emailAddress));
        //new javax.mail.internet.InternetAddress("glarocca75@gmail.com")); // <== Change here!

        // Set Subject: header field
        message.setSubject(" Chipster Account Generator service notification ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://scilla.man.poznan.pl:8080/confluence/download/attachments/5505438/egi_logo.png\" width=\"100\">"
                + "</H4><hr><br/>" + "<b>Description:</b> " + ApplicationAcronym
                + " notification service <br/><br/>"
                + "<i>A request to create a new temporary chipster account has been successfully sent from the LToS Science Gateway</i><br/><br/>"
                + "<b>Chipster Front Node:</b> " + chipster_HOST + "<br/>" + "<b>Credentials:</b> " + credential
                + "<br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>" + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Catania Science Gateway (CSG) tailored for the EGI Long of Tail Science.<br/><br/>",
                "text/html");

        // Send message
        javax.mail.Transport.send(message);
    } catch (javax.mail.MessagingException ex) {
        Logger.getLogger(Chipster.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testSimpleAttachment3() throws MessagingException, IOException {
    Mailet mailet = initMailet();//from w w  w.java2  s.c o m

    // System.setProperty("mail.mime.decodefilename", "true");

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?=");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();

    // message.writeTo(System.out);
    // System.out.println("--------------------------\n\n\n");

    Mail mail = FakeMail.builder().mimeMessage(message).build();

    mailet.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" });
    // String res = rawMessage.toString();

    @SuppressWarnings("unchecked")
    Collection<String> c = (Collection<String>) mail
            .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY);
    Assert.assertNotNull(c);

    Assert.assertEquals(1, c.size());

    String name = c.iterator().next();
    // System.out.println("--------------------------\n\n\n");
    // System.out.println(name);

    Assert.assertTrue(name.startsWith("e_Pubblicita_e_vietata_Milano9052"));

    File f = new File("./" + name);
    try {
        InputStream is = new FileInputStream(f);
        String savedFile = toString(is);
        is.close();
        Assert.assertEquals(body, savedFile);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:trendplot.TrendPlot.java

private void emailResults() throws IOException, WebUtilException {
    emailStart = System.currentTimeMillis();

    ViewerConfig vc = new ViewerConfig();
    if (!config.isEmpty()) {
        vc.setConfigFileName(config);/*from w  w w .j a  va  2 s.  co m*/
    }
    vc.readConfig();
    String host = vc.get("webserver");
    if (host == null || host.isEmpty()) {
        host = "ldvw.ligo.caltech.edu";
    }
    String servlet = vc.get("servlet");
    if (servlet == null || servlet.isEmpty()) {
        servlet = "ldvw/view";
    }
    PageItemList msg = new PageItemList();

    if (!imgIds.isEmpty()) {
        msg.add(new PageItemHeader("The following results are available:", 3));
        PageTable tbl = new PageTable();
        for (int img = 0; img < imgIds.size(); img++) {
            PageTableRow row = new PageTableRow();
            row.add(descriptions.get(img));
            Integer imgId = imgIds.get(img);
            String url = "https://" + host + "/" + servlet + "?act=getimg&amp;imgId=" + imgId.toString();
            PageItemTextLink link = new PageItemTextLink(url, "link");
            row.add(link);
            tbl.addRow(row);
        }
        msg.add(tbl);
        msg.addBlankLines(2);

        String groupIntro = String.format("These images have also been added to the %1$s group.<br>", group);
        msg.add(new PageItemString(groupIntro, false));
        String groupUrl = String.format(
                "https://%1$s/%2$s?act=imagehistory&amp;group=%3$s" + "&amp;usrSel=%4$s", host, servlet, group,
                user);
        PageItemTextLink groupLink = new PageItemTextLink(groupUrl, "Click for image group page.");
        msg.add(groupLink);
        msg.addBlankLines(2);
    } else if (!checkOnly) {
        msg.add("Sorry but no images were produced.");
        msg.addBlankLines(2);
    }
    if (verbose || imgIds.isEmpty()) {
        msg.add(new PageItemString("<br>Stdout:<br><br>", false));
        String outText = outStringWriter.toString().replace("\n", "<br>\n");
        msg.add(new PageItemString(outText, false));

        msg.add(new PageItemString("<br>Stderr:<br><br>", false));
        outText = errStringWriter.toString().replace("\n", "<br>\n");
        msg.add(new PageItemString(outText, false));
    }
    msg.add(new PageItemString("<br><br>Sincerly,<br>The LigoDV-web group", false));

    Float condor = (startTime - qtime) / 1000.f;
    String condorTime = qtime == 0 ? "?" : String.format("%1$.2f", condor);
    Float overhead = (transferStart - startTime) / 1000.f;
    Float xfer = (plotStart - transferStart) / 1000.f;
    Float plot = (emailStart - plotStart) / 1000.f;
    String timing = String.format(
            "Timing: queue: %1$s, overhead: %2$.2f, data collection: %3$.2f, " + "plot: %4$.2f seconds",
            condorTime, overhead, xfer, plot);
    outPrintWriter.println(timing);
    msg.addBlankLines(2);
    msg.add(new PageItemString(timing, false));
    msg.addBlankLines(1);

    String msgText = msg.getHtml();

    Properties fMailServerConfig;
    fMailServerConfig = new Properties();
    fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu");
    fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu");

    Session session = Session.getDefaultInstance(fMailServerConfig, null);
    MimeMessage message = new MimeMessage(session);
    try {
        //the "from" address may be set in code, or set in the
        //config file under "mail.from" ; here, the latter style is used
        message.setFrom(new InternetAddress("areeda@ligo.caltech.edu"));

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

        message.setSubject("Trend plot results are available.");
        message.setText(msgText, "utf-8", "html");
        Transport.send(message);
        outPrintWriter.format("Email sent to %1$s\n", email);
        errPrintWriter.println("Email message:");
        errPrintWriter.println(msgText);
    } catch (MessagingException ex) {
        throw new WebUtilException("Cannot send email. " + ex);
    }
}

From source file:trendplot.TrendPlot.java

private void testEmail() {
    Properties fMailServerConfig;
    fMailServerConfig = new Properties();
    fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu");
    fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu");

    Session session = Session.getDefaultInstance(fMailServerConfig, null);
    MimeMessage message = new MimeMessage(session);
    try {/*from w  w w  .  j  a v  a 2s.c  om*/
        //the "from" address may be set in code, or set in the
        //config file under "mail.from" ; here, the latter style is used
        message.setFrom(new InternetAddress("areeda@ligo.caltech.edu"));
        String email = "joe@areeda.com";

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        String msg = "<h3>this is a test</h3>";
        message.setSubject("Test email");
        message.setText(msg, "utf-8", "html");
        Transport.send(message);
        System.out.format("Email sent to %1$s\n", email);
    } catch (MessagingException ex) {
        System.err.format("Exception: %1$s: %2$s", ex.getClass().getSimpleName(), ex.getLocalizedMessage());
    }

}

From source file:org.grouter.common.mail.MailHandler.java

/**
 * Creates a multipart email with html and plain text email body to fallback to if
 * email client do not handle html base emails.
 *
 * @param mimeMessage//from  ww w  . j ava  2s .c o  m
 * @param dto
 * @throws MessagingException
 */
private void createHtmlAndPlainTextBody(MimeMessage mimeMessage, MailDto dto) throws MessagingException {
    if (StringUtils.isNotEmpty(dto.getHtmlTextBody())) {
        mimeMessage.setContentID(MailDto.CONTENT_TYPE_MULTIPART_ALTERNATIVE);

        // Create your text message part
        BodyPart plainBodyPart = new MimeBodyPart();
        plainBodyPart.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN);

        // Create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart("alternative");
        multipart.addBodyPart(plainBodyPart);

        StringBuilder sb = new StringBuilder();
        sb.append(PRE_HTML_HEADER);
        sb.append(dto.getSubject()).append("\n");
        sb.append(POST_HTML_HEADER);
        sb.append(dto.getHtmlTextBody());
        sb.append(END_HTML);

        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(sb.toString(), MailDto.CONTENT_TYPE_TEXT_HTML);

        // Add html part to multi part
        multipart.addBodyPart(htmlBodyPart);
        mimeMessage.setContent(multipart);
    } else {
        mimeMessage.setSubject(dto.getSubject());
        mimeMessage.setText(dto.getPlainTextBody());
        mimeMessage.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN);
    }

}

From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public MimeMessage transform(MimeMessage message) throws MessagingException {
    MimeBodyPart sentToBodyPart = newSentToBodyPart(message);
    MimeBodyPart originalBodyPart = newOriginalBodyPart(message);

    // create a new multipart content for this message.
    MimeMultipart multipart = new MimeMultipart(EmailUtil.SUBTYPE_MIXED);

    // add the parts to the body.
    multipart.addBodyPart(originalBodyPart);
    multipart.addBodyPart(sentToBodyPart);

    // get the new values for all of the headers.
    InternetAddress newFromAddress = newFromAddress(message);
    InternetAddress[] newToAddresses = newToAddresses(message);
    InternetAddress[] newCcAddresses = newCcAddresses(message);
    InternetAddress[] newBccAddresses = newBccAddresses(message);
    String newSubject = newSubject(message);

    // update the message.
    message.setFrom(newFromAddress);/*from  w  w  w  .  j a  va 2  s .  c om*/
    message.setRecipients(Message.RecipientType.TO, newToAddresses);
    message.setRecipients(Message.RecipientType.CC, newCcAddresses);
    message.setRecipients(Message.RecipientType.BCC, newBccAddresses);
    message.setSubject(newSubject);
    message.setContent(multipart);

    // save the message.
    message.saveChanges();

    if (getLogProperty()) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            message.writeTo(out);
            log.info("Email Message Sent:\n{}", out.toString());
        } catch (IOException ioe) {
            throw new MessagingException("Exception thrown while writing message to log.", ioe);
        }
    }
    if (!getSendProperty()) {
        message = null;
    }

    // return the message.
    return message;
}