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
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.
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);
Source: Stackoverflow.com