I am using JavaMail api in order to send email, but when i send email with attachment i want to send attachments only base64 view. Here is i implemented code, it works fine but sometimes attachment is not converting to base64.
我正在使用JavaMail api发送电子邮件,但是当我发送带附件的电子邮件时我想发送附件只有base64视图。这是我实现的代码,它工作正常,但有时附件不转换为base64。
private static Multipart createMultipartMixed(Email email, List<File> attachmentFiles, Context context) throws MessagingException {
Multipart multipartMixed = new MimeMultipart("mixed");
MimeBodyPart multipartAlternativeBodyPart = new MimeBodyPart();
multipartAlternativeBodyPart.setContent(createMultipartAlternative(email, context));
multipartMixed.addBodyPart(multipartAlternativeBodyPart);
for (File file : attachmentFiles) {
MimeBodyPart attachFilePart = createAttachmentBodyPart(file, true, null);
multipartMixed.addBodyPart(attachFilePart);
}
return multipartMixed;
}
private static MimeBodyPart createAttachmentBodyPart(File file, boolean isAttachmentDisposition, String cid)
throws MessagingException {
MimeBodyPart attachFilePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file.getAbsolutePath());
attachFilePart.setDataHandler(new DataHandler(fds));
try {
attachFilePart.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));
if(isAttachmentDisposition) {
attachFilePart.setDisposition(Part.ATTACHMENT);
} else {
attachFilePart.setDisposition(Part.INLINE);
attachFilePart.setContentID("<" + cid + ">");
}
} catch (UnsupportedEncodingException e) {
LOGGER.error("UnsupportedEncodingException: " + e.getMessage());
e.printStackTrace();
attachFilePart.setFileName(fds.getName());
}
return attachFilePart;
}
Why sometimes attachment is not in base64 view in Mime file? Thank you in advance
为什么有时附件不在Mime文件的base64视图中?先感谢您
1 个解决方案
#1
2
JavaMail chooses the Content-Transfer-Encoding based on the actual content of the body part. If the content is mostly text, it's not going to use base64.
JavaMail根据正文部分的实际内容选择Content-Transfer-Encoding。如果内容主要是文本,则不会使用base64。
If there's some reason to force it to choose base64 (e.g., the message will be processed by a broken program that always expects the attachment to be base64 encoded), you can force the choice of transfer encoding:
如果有某种原因迫使它选择base64(例如,消息将由一个总是希望附件是base64编码的损坏的程序处理),你可以强制选择传输编码:
attachFilePart.setHeader("Content-Transfer-Encoding", "base64");
#1
2
JavaMail chooses the Content-Transfer-Encoding based on the actual content of the body part. If the content is mostly text, it's not going to use base64.
JavaMail根据正文部分的实际内容选择Content-Transfer-Encoding。如果内容主要是文本,则不会使用base64。
If there's some reason to force it to choose base64 (e.g., the message will be processed by a broken program that always expects the attachment to be base64 encoded), you can force the choice of transfer encoding:
如果有某种原因迫使它选择base64(例如,消息将由一个总是希望附件是base64编码的损坏的程序处理),你可以强制选择传输编码:
attachFilePart.setHeader("Content-Transfer-Encoding", "base64");