Sending an HTML email message
Sometimes you need to include rich content in your mail body, such as formatted text and images. You can use HTML instead of plain text as the body of your email. The following example alters the previous one to do this using the Java Mail API:
.... Message message = new MimeMessage(session); // filling mail attributes message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject("Mail Subject"); message.setContent("<html>Hello <b>World</b></html>", "text/html; charset=utf-8"); ....
As you can see, we have used the setContent
method of the message object, rather than the setText
method. setContent
has been passed two parameters:
- The content object, which is a string with HTML content
- The MIME type of the object, which is
text/html.
By using...