Search code examples
htmljakarta-mailmultipartform-data

Multipart nested into Multipart Embedded encodded image base 64 javamail


I have an email which has multipart/alternative part . Into this part there is a multipart/related part; Into this multipart/realted part I have an text/html and image/jpg. I'm trying to extract those two parts and adda tag to the html part message and compose it again. The html and image part should look the same. I have inserted only a tag into the html part. But when I try to compose the message again I somehow cannot manage. I don't know how to recreate this multipart nested into another multipart. I have this
into the original email and again into my htmlmessageBodyPart. But when my recreated e-mail is displayed the image is broken.

below is part of my sender class. It works ok with attachments, plain text and so on.Any help will be appreciated!

 // create a multi-part to combine the parts
        Multipart multipart = new MimeMultipart(
                setSubtype(origMessage));

        // create a new message part for body text
        MimeBodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText(message);
            messageBodyPart.setDisposition(MimePart.INLINE);
            multipart.addBodyPart(messageBodyPart);

            BodyPart htmlmessageBodyPart = new MimeBodyPart();
            htmlmessageBodyPart.setContent(html, content);
            htmlmessageBodyPart.setDisposition("null");
            multipart.addBodyPart(htmlmessageBodyPart);

        MimeBodyPart imageBodyPart = new MimeBodyPart();
        imageBodyPart.setHeader("Content_ID",
                "<[email protected]>");
        imageBodyPart.setDisposition(MimePart.INLINE);
        imageBodyPart.setContent(html,"image/png");
        imageBodyPart.attachFile(file);
        multipart.addBodyPart(imageBodyPart);

        msg.setContent(multipart1);

        Transport.send(msg);

Solution

  • Your original message has an extra level of nested multiparts that's missing from your code.

    // add text/plain part to multipart, then...
    Multipart innerMultipart = new MimeMulpart("related");
    // add html and image parts to innerMultipart
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setContent(innerMultipart);
    multipart.addBodyPart(mbp);