How do I send mail with both plain text as well as HTML text so that each mail reader can choose the format appropriate for it?

Tim picture Tim · Jul 20, 2011 · Viewed 20.9k times · Source

From http://www.oracle.com/technetwork/java/faq-135477.html#sendmpa:

You'll want to send a MIME multipart/alternative message. You construct such a message essentially the same way you construct a multipart/mixed message, using a MimeMultipart object constructed using new MimeMultipart("alternative"). You then insert the text/plain body part as the first part in the multpart and insert the text/html body part as the second part in the multipart. You'll need to construct the plain and html parts yourself to have appropriate content. See RFC2046 for details of the structure of such a message.

Can someone show me some sample code for this?

Answer

zacheusz picture zacheusz · Jul 20, 2011

This is a part of my own code:

final Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(senderAddress, senderDisplayName));
msg.addRecipient(Message.RecipientType.TO,
        new InternetAddress(m.getRecipient(), m.getRecipientDisplayName()));
msg.setSubject(m.getSubject());
// Unformatted text version
final MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(m.getText(), "text/plain"); 
// HTML version
final MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(m.getHtml(), "text/html");
// Create the Multipart.  Add BodyParts to it.
final Multipart mp = new MimeMultipart("alternative");
mp.addBodyPart(textPart);
mp.addBodyPart(htmlPart);
// Set Multipart as the message's content
msg.setContent(mp);
LOGGER.log(Level.FINEST, "Sending email {0}", m);
Transport.send(msg);

Where m is an instance of my own class.