Search code examples
javajakarta-mail

Include Image in an email without attachments using java


I want to add an image to an email along with some text without having to attach the image in the email. Would this be possible ?

I have managed to do the following so far but it is sent with an attachment and also the image in the mail. I want it without an attachment but as a part of the mail

 `Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(emailID));
        message.setSubject("Password Reset");

                    Multipart multipart = new MimeMultipart("related");


                    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent("<html><body>Hi<img src=\"cid:the-img-1\"/></body></html>", "text/html");

    multipart.addBodyPart(htmlPart);


    BodyPart imgPart=new MimeBodyPart();

    // Loading the image
    DataSource ds=new FileDataSource("C:\\Users\\XYZ\\Desktop\\images.jpg");
    imgPart.setDataHandler(new DataHandler(ds));

    //Setting the header
    imgPart.setHeader("Content-ID","the-img-1");

    multipart.addBodyPart(imgPart);

    // attaching the multi-part to the message

    message.setContent(multipart);


        Transport.send(message);`

Solution

  • You need to construct a multipart/related message.