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 (SendEmail4.java) that sends a message having html content is shown below:
//SendEmail4.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail4 {
public static void main(String [] args) {
String to = “usr.some@gmail.com”;
String mailHost = “smtp.gmail.com”;
final String user = “usr.some@gmail.com”, password = “some.usr”;
Properties props = new Properties();
props.setProperty(“mail.smtp.host”, 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);
}
});
//session.setDebug(true);
try{
MimeMessage msg = new MimeMessage(session);
msg.setFrom(user);
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”);
Transport.send(msg);
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.