Java Email with HTML Content

Sending messages having html content needs a little additional work. All we need to do is to specify content type as text/html in setContent() method. For example, the following piece of code sets a <h2> element to the content:

msg.setContent(”<h2>Mail with html body.</h2>”,”text/html”);

The complete source code of a program ( that sends a message having html content is shown below:


import java.util.*;

import javax.mail.*;

import javax.mail.internet.*;

public class SendEmail4 {

public static void main(String [] args) {

String to = “”;

String mailHost = “”;

final String user = “”, password = “some.usr”;

Properties props = new Properties();

props.setProperty(“”, mailHost);

props.put(“mail.smtp.auth”, “true”);

props.put(“mail.smtp.starttls.enable”, “true”);

Session session = Session.getInstance(props, new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(user,password);





MimeMessage msg = new MimeMessage(session);


msg.addRecipients(Message.RecipientType.TO, to);

msg.setSubject(”Mail with html body”);

msg.setText(”Test message”);

msg.setContent(”<h2>Mail with html body.</h2>”,”text/html”);


System.out.println(”msg sent….”);

}catch (Exception e) { e.printStackTrace();




Compile and run the program as described previously. A sample output is shown in Figure 15.7:

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *