Categories
Java

generate HTML MimeMessage with Java

If you want to send some emails with your Java application, you may also want to format these mails using HTML. To achieve this, you have to build a correct multipart message defined in RFC 2045 and RFC 2046 and some more.

The header information of an email, like recipient, subject, etc., differs not from plain text mails:

MimeMessage mimeMessage = new MimeMessage((Session) null);
mimeMessage.setFrom("foo@example.com");
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("bar@example.com", "Mr. Bar"));
mimeMessage.setSubject("My Subject", "UTF-8");

You should use a common character encoding for subjects. UTF-8 is a recommended and public supported one. This also applies for message content.

Now create the message body:

//create multipart
MimeMultipart content = new MimeMultipart("alternative");
//create simple textpart; content-type text/plain
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("content which is displayed, if mail client did not support HTML mails", "UTF-8");
//adds text part to multipart
content.addBodyPart(textPart);
//create html textpart; content-type text/html
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setText("<html><body><p>My Mailtext</p></body></html>, "UTF-8", "html");
content.addBodyPart(htmlPart);
//set content of mail to be multipart
mimeMessage.setContent(content);