Search code examples
javaimageembedmimejakarta-mail

how to embed multiple images while sending html email using Java mail


I'm trying to send email from javamail. I'm embeding the images and using CID. But the problem is how do I embed multiple images in a single message. if I try to add in header.. it is just taking the last set header. how do I add multiple images and reference using CID.

MimeMultipart multipart = new MimeMultipart("related");

    // first part  (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
//    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<H1>Hello</H1><br/> <p align=center><img src=\"cid:senny\"> </p>";
    htmlText+="<p align=center><img src=\"cid:senny\"> </p>";
    htmlText+="<p align=center><img src=\"cid:image\"> </p>";
    messageBodyPart.setContent(htmlText, "text/html");

    // add it
    multipart.addBodyPart(messageBodyPart);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource
      ("C:\\images\\cec_header_457.png");
    DataSource fds1 = new FileDataSource
    ("C:\\images\\cec_header_420.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setDataHandler(new DataHandler(fds1));
    messageBodyPart.addHeader("Content-ID","<image>");
    messageBodyPart.addHeader("Content-ID","<senny>");
    // add it
    multipart.addBodyPart(messageBodyPart);

    // put everything together
    message.setContent(multipart);

Solution

  • Each image needs to be its own MimeBodyPart, break up this code,

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource
      ("C:\\images\\cec_header_457.png");
    DataSource fds1 = new FileDataSource
    ("C:\\images\\cec_header_420.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setDataHandler(new DataHandler(fds1));
    messageBodyPart.addHeader("Content-ID","<image>");
    messageBodyPart.addHeader("Content-ID","<senny>");
    // add it
    multipart.addBodyPart(messageBodyPart);
    

    Into two multi parts, something like

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds1 = new FileDataSource
    ("C:\\images\\cec_header_420.png");
    messageBodyPart.setDataHandler(new DataHandler(fds1));
    messageBodyPart.addHeader("Content-ID","<senny>");
    // add it
    multipart.addBodyPart(messageBodyPart);
    
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource
      ("C:\\images\\cec_header_457.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.addHeader("Content-ID","<image>");
    // add it
    multipart.addBodyPart(messageBodyPart);