How do I send an HTML email?

Thang Pham picture Thang Pham · Feb 21, 2011 · Viewed 205.1k times · Source

I have successfully sent email in my web application using JMS, but the result only displays in plain text. I want the content to be able to display html. How do I do it? Here is roughly what I have:

Message msg = new MimeMessage(mailSession);
try{
    msg.setSubject("Test Notification");
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(sentTo, false));
    String message = "<div style=\"color:red;\">BRIDGEYE</div>";
    msg.setContent(message, "text/html; charset=utf-8");
    msg.setSentDate(new Date());
    Transport.send(msg);
}catch(MessagingException me){
    logger.log(Level.SEVERE, "sendEmailNotification: {0}", me.getMessage());
}

Answer

BalusC picture BalusC · Feb 21, 2011

As per the Javadoc, the MimeMessage#setText() sets a default mime type of text/plain, while you need text/html. Rather use MimeMessage#setContent() instead.

message.setContent(someHtmlMessage, "text/html; charset=utf-8");

For additional details, see: