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?
GroupMail allows senders to send both an HTML and plain-text version of their email at the same time. This is done using a format called Multi-Part MIME. When a multi-part MIME email (read: an email that includes both an HTML and plain-text part) is created in GroupMail, they will be sent out together as one message.
You can apply the following settings to forward the message in HTML format: “Settings” -> “Preferences” tab -> “Composing Messages” -> “Compose HTML messages” -> Select “on forward or reply to HTML message” under “Compose HTML messages” and save.
This is the most efficient way of doing the task. Create a dummy element and assign it to a variable. We can extract later using the element objects. Assign the HTML text to innerHTML of the dummy element and we will get the plain text from the text element objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With