JavaMail base64 encoding

你。 提交于 2019-12-23 17:48:01

问题


I have some Java code which sends out an email with code somewhat like the following:

MimeBodyPart part = new MimeBodyPart();
part.setContent(htmlString, "text/html; charset=\"UTF-8\"");
part.setHeader("MIME-Version", "1.0");
part.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
part.setHeader("Importance", severityVal);

mimeMultiPart.addBodyPart(htmlPart);
mimeMessage.setContent(mimeMultiPart);

... and so on.

How can I encode the "part" MimeBodyPart in base64 for this outgoing email?


回答1:


From the docs:

Q: Even though JavaMail does all the encoding and decoding for me, I need to manually control the encoding for some body parts. A: In the rare case that you need to control the encoding, there are several ways to override JavaMail's default behavior. A simple approach is as follows. After creating the entire message, call msg.saveChanges() and then use something like mbp.setHeader("Content-Transfer-Encoding", "base64") to force base64 encoding for the given body part.

Another approach is to subclass MimeBodyPart and override the updateHeaders method so that it first calls super.updateHeaders() and then sets the Content-Transfer-Encoding header as above.




回答2:


simply add this statement:

part.setHeader("Content-Transfer-Encoding", "base64");

after the lines of code that set part.setDataHandler(..) or part.setContent(...), and the dataSource/Handler will adapt itself to match the content transfer encoding you just specified for the body part.

You may also want to consider setting the headers by the same token, e.g.:

part.setHeader("Content-Type", "application/octet-stream");


来源:https://stackoverflow.com/questions/9124554/javamail-base64-encoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!