我正在使用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;
}
为什么有时附件不在Mime文件的base64视图中?提前谢谢
答案 0 :(得分:2)
JavaMail根据正文部分的实际内容选择Content-Transfer-Encoding。如果内容主要是文本,则不会使用base64。
如果有某种理由迫使它选择base64(例如,消息将由一个总是希望附件为base64编码的损坏程序处理),则可以强制选择传输编码:
attachFilePart.setHeader("Content-Transfer-Encoding", "base64");