37

The program below shows an unexpected return value for HTML multipart MIME type. Why does this program print text/plain and not text/html?

public class Main {
  public static void main(String[] args) throws javax.mail.MessagingException, java.io.IOException {
    javax.mail.internet.MimeBodyPart mime_body_part = new javax.mail.internet.MimeBodyPart();
    mime_body_part.setContent("<h1>foo</h1>", "text/html");
    System.out.println(mime_body_part.getContentType());
  }
}

I have tried numerous alternative ways including setting a ByteArrayDataSource wrapped in a DataHandler, but to no avail. The same thing happens when I try this with a MimeMessage instead of a MimeBodyPart.

To compile and run on Linux:

javac -classpath .:activation.jar:mail.jar Main.java
java -classpath .:activation.jar:mail.jar Main

8 Answers 8

64

Call MimeMessage.saveChanges() on the enclosing message, which will update the headers by cascading down the MIME structure into a call to MimeBodyPart.updateHeaders() on your body part. It's this updateHeaders call that transfers the content type from the DataHandler to the part's MIME Content-Type header.

When you set the content of a MimeBodyPart, JavaMail internally (and not obviously) creates a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated immediately.

There's no straightforward way to do it in your test program, since you don't have a containing MimeMessage and MimeBodyPart.updateHeaders() isn't public.


Here's a working example that illuminates expected and unexpected outputs:

public class MailTest {

  public static void main( String[] args ) throws Exception {
    Session mailSession = Session.getInstance( new Properties() );
    Transport transport = mailSession.getTransport();

    String text = "Hello, World";
    String html = "<h1>" + text + "</h1>";

    MimeMessage message = new MimeMessage( mailSession );
    Multipart multipart = new MimeMultipart( "alternative" );

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText( text, "utf-8" );

    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent( html, "text/html; charset=utf-8" );

    multipart.addBodyPart( textPart );
    multipart.addBodyPart( htmlPart );
    message.setContent( multipart );

    // Unexpected output.
    System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
    System.out.println( "HTML Content Type: " + htmlPart.getContentType() );

    // Required magic (violates principle of least astonishment).
    message.saveChanges();

    // Output now correct.    
    System.out.println( "TEXT = text/plain: " + textPart.isMimeType( "text/plain" ) );
    System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
    System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
    System.out.println( "HTML Data Handler: " + htmlPart.getDataHandler().getContentType() );
  }
}
2
  • 1
    update - this worked fine for my test program but in my real code it did not. the difference was that the real code was obtaining a MimeMessage object that was created by the mail system, then updating a part, and then calling MimeMessage.saveChanges(). this was still not changing the mimetype (although the content was changed even before calling .saveChanges()). SOLUTION: i created a new MimeMessage(old_mime_message) object from the old one, changed the content and type, then called .saveChanges() and it worked fine for me. Feb 18, 2011 at 0:05
  • 1
    MimeMessage.saveChanges() was the magic I needed to make our junit tests to pass. Apr 15, 2011 at 9:37
29

Don't know why (the method is not documented), but by looking at the source code, this line should do it :

mime_body_part.setHeader("Content-Type", "text/html");
1
  • 4
    thank you - i am grateful for your help. i chose a different answer above since it better fits the way the libraries are intended to be used. but your answer was valuable to me in making immediate progress in getting an urgent task done. thanks again. Feb 17, 2011 at 23:12
7

Try with this:

msg.setContent(email.getBody(), "text/html; charset=ISO-8859-1");
5

What about using:

mime_body_part.setHeader("Content-Type", "text/html");

In the documentation of getContentType it says that the value returned is found using getHeader(name). So if you set the header using setHeader I guess everything should be fine.

1
  • 1
    thank you - i am grateful for your help. i chose a different answer above since it better fits the way the libraries are intended to be used. but your answer was valuable to me in making immediate progress in getting an urgent task done. thanks again. Feb 17, 2011 at 23:11
4

There is a method setText() which takes 3 arguments :

public void setText(String text, String charset, String subtype)
    throws MessagingException

Parameters:

text - the text content to set
charset - the charset to use for the text
subtype - the MIME subtype to use (e.g., "html")

NOTE: the subtype takes text after / in MIME types so for ex.

  • text/html would be html
  • text/css would be css
  • and so on..
1
2

For me, I set two times:

(MimeBodyPart)messageBodyPart.setContent(content, text/html)
(Multipart)multipart.addBodyPart(messageBodyPart)
(MimeMessage)msg.setContent(multipart, text/html)

and its been working fine.

2

Using "<h1>STRING<h1>".getBytes(); you can create a ByteArrayDataSource with content-type and set setDataHandler in your MimeBodyPart

try:

String html "Test JavaMail API example. <br><br> Regards, <br>Ivonei Jr"
byte[] bytes = html.getBytes(); 
DataSource dataSourceHtml= new ByteArrayDataSource(bytes, "text/html");
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setDataHandler(new DataHandler(dataSourceHtml));

MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(bodyPart);
1

I have used below code in my SpringBoot application.

MimeMessage message = sender.createMimeMessage();
message.setContent(message, "text/html");
MimeMessageHelper helper = new MimeMessageHelper(message);

helper.setFrom(fromAddress);
helper.setTo(toAddress);
helper.setSubject(mailSubject);
helper.setText(mailText, true);

sender.send(message);
1
  • Adding "message.setContent(message, "text/html");" and "helper.setText(mailText, true);" worked for me. Oct 21, 2019 at 19:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.