How to set MimeBodyPart ContentType to "text/html"?

mimemessage setcontent
mimebodypart example
mimebodypart attachfile
mimebodypart java 8
messagebodypart
format email body in java
mimemessage html content
how to send html table in email body in java

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

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() );
  }
}

javax.mail.internet.MimeBodyPart.setContent java code examples , Returns new {@link MimeBodyPart} with content set as msgMultipart. * * @param msgMultipart {@link setContent(html, "text/html; charset=utf-8"); multiPart. Sets the "filename" parameter of the "Content-Disposition" header field of this body part. For compatibility with older mailers, the "name" parameter of the "Content-Type" header is also set. If the mail.mime.encodefilename System property is set to true, the MimeUtility.encodeText method will be used to encode the filename. While such encoding is not supported by the MIME spec, many mailers use this technique to support non-ASCII characters in filenames.

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");

Java Code Examples javax.mail.internet.MimeBodyPart.setContent, Add a multipart/alternative part to message body * * @param plainContent * the setContent(content, "text/html;charset=UTF-8"); MimeBodyPart attach = new  Sets the "filename" parameter of the "Content-Disposition" header field of this body part. For compatibility with older mailers, the "name" parameter of the "Content-Type" header is also set. If the mail.mime.encodefilename System property is set to true, the MimeUtility.encodeText method will be used to encode the filename. While such encoding is not supported by the MIME spec, many mailers use this technique to support non-ASCII characters in filenames.

Try with this:

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

Java Code Examples javax.mail.internet.ContentType, Get the character set of a regular part * * @param partIndex * the index of the associated type MimeBodyPart dataPart = new MimeBodyPart(); ContentType  MimeBodyPart.ContentType Property The Content-type of the email, for example text/html; or text/plain;. This property overrides the value set for BodyFormat

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.

MimeBodyPart (Java(TM) EE 7 Specification APIs), Convenience method that sets the given String as this part's content, with a MIME type of "text/plain" and the specified charset. void, setText(String text, String  The following are Jave code examples for showing how to use setText() of the javax.mail.internet.MimeBodyPart class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.

JavaMail set content to utf-8 (Java API forum at Coderanch), JavaMail set content to utf-8 I'm using javamail to send email notification which contains chinese or Setting the Subject and Content Type The following are top voted examples for showing how to use javax.mail.internet.MimeBodyPart.These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.

MimeBodyPart (GNU JavaMail API documentation), Sets the content of this part using the specified text, and with a MIME type of "text/ plain". void, setText(java.lang.String text, java.lang.String charset). Sets the  Content Type. Content Type is also known as MIME (Multipurpose internet Mail Extension)Type. It is a HTTP header that provides the description about what are you sending to the browser. MIME is an internet standard that is used for extending the limited capabilities of email by allowing the insertion of sounds, images and text in a message.

MimeMultipart (GNU JavaMail API documentation), Create and return a MimeBodyPart object to represent a body part parsed from and this string is set up as the "boundary" parameter for the contentType field. The Content-Type header is used to indicate the media type of the resource. The media type is a string sent along with the file indicating the format of the file. For example, for image file its media type will be like image/png or image/jpg, etc.

Java Examples for javax.mail.internet.MimeBodyPart, @param name The name that will be set in the filename header * field. Structure of test message and content type: * <p> * Message (multipart/mixed)  The following are Jave code examples for showing how to use setContent() of the javax.mail.internet.MimeBodyPart class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.

Comments
  • 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.
  • MimeMessage.saveChanges() was the magic I needed to make our junit tests to pass.
  • 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.
  • 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.
  • docs.oracle.com/javaee/6/api/javax/mail/internet/…, java.lang.String, java.lang.String)
  • Adding "message.setContent(message, "text/html");" and "helper.setText(mailText, true);" worked for me.