JavaMail base64 编码
我有一些 Java 代码,它会发送一封电子邮件,其代码有点类似于以下内容:
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);
...等等。
如何对这封外发电子邮件的“部分”MimeBodyPart 进行 Base64 编码?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 docs:
问:尽管 JavaMail 完成了所有编码和对我来说,解码时,我需要手动控制某些身体部位的编码。
答:在极少数情况下,您需要控制编码,有多种方法可以覆盖 JavaMail 的默认行为。一个简单的方法如下。创建整个消息后,调用
msg.saveChanges()
,然后使用mbp.setHeader("Content-Transfer-Encoding", "base64")
强制使用 base64给定身体部位的编码。另一种方法是子类化
MimeBodyPart
并重写updateHeaders
方法,以便它首先调用super.updateHeaders()
,然后设置Content -Transfer-Encoding
标头如上。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 likembp.setHeader("Content-Transfer-Encoding", "base64")
to force base64 encoding for the given body part.Another approach is to subclass
MimeBodyPart
and override theupdateHeaders
method so that it first callssuper.updateHeaders()
and then sets theContent-Transfer-Encoding
header as above.只需添加以下语句:
在设置
part.setDataHandler(..)
或part.setContent(...)
的代码行之后,并且 dataSource/Handler 将进行自我调整以匹配您刚刚为正文部分指定的内容传输编码。您可能还想考虑通过相同的方式设置标头,例如:
simply add this statement:
after the lines of code that set
part.setDataHandler(..)
orpart.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.: