[java] How to set MimeBodyPart ContentType to "text/html"?

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

This question is related to java mime jakarta-mail mime-types

The answer is


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..

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.


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

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.


Try with this:

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

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

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to mime

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff) Nginx fails to load css files Which MIME type to use for a binary file that's specific to my program? embedding image in html email How to set MimeBodyPart ContentType to "text/html"? Mail multipart/alternative vs multipart/mixed Proper MIME type for OTF fonts How can I find out a file's MIME type (Content-Type)? Detect when browser receives file download Get MIME type from filename extension

Examples related to jakarta-mail

Base64: java.lang.IllegalArgumentException: Illegal character javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25 Solve error javax.mail.AuthenticationFailedException java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail Javamail Could not convert socket to TLS GMail Send Mail to multiple Recipients in java Error - trustAnchors parameter must be non-empty javax.mail.AuthenticationFailedException: failed to connect, no password specified? package javax.mail and javax.mail.internet do not exist How do I send an HTML email?

Examples related to mime-types

Stylesheet not loaded because of MIME-type Is the MIME type 'image/jpg' the same as 'image/jpeg'? Proper MIME type for .woff2 fonts How to check file MIME type with javascript before upload? Correct MIME Type for favicon.ico? Right mime type for SVG images with fonts embedded Which mime type should I use for mp3 Correct mime type for .mp4 What does "Content-type: application/json; charset=utf-8" really mean? Add MIME mapping in web.config for IIS Express