Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Tags:

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?

like image 908
Tim Avatar asked Jul 20 '11 01:07

Tim


People also ask

How do you send plain text and HTML email simultaneously?

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.

How do I forward an HTML email without losing formatting?

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.

How do you send HTML to plain text?

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.


1 Answers

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.

like image 195
zacheusz Avatar answered Nov 01 '22 06:11

zacheusz