javaemailjakarta-mail

How do I send an HTML email?


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.setText(message);
    msg.setSentDate(new Date());
    Transport.send(msg);
}catch(MessagingException me){
    logger.log(Level.SEVERE, "sendEmailNotification: {0}", me.getMessage());
}

Solution

  • As per the Javadoc, the MimeMessage#setText() sets a default mime type of text/plain.

    Convenience method that sets the given String as this part's content, with a MIME type of "text/plain".

    But you ultimately need text/html. Rather use MimeMessage#setContent() instead.

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

    See also: