Search code examples
javaandroidbase64jakarta-mailemail-attachments

JavaMail Add attachement to Mime body as base64


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.

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


Solution

  • 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.

    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:

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