Embedding attached images in HTML emails

后端 未结 7 1650
既然无缘
既然无缘 2020-12-05 08:15

If I attach an image to an email, how can I place it in the HTML content? I tried just using the filename as the image source but that doesn\'t seem to work.

7条回答
  •  感动是毒
    2020-12-05 08:36

    The answer to your question is in the spring docs here.

     mailSender.send(new MimeMessagePreparator() {
       public void prepare(MimeMessage mimeMessage) throws MessagingException {
         MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
         message.setFrom("me@mail.com");
         message.setTo("you@mail.com");
         message.setSubject("my subject");
         message.setText("my text ", true);
         message.addInline("myLogo", new ClassPathResource("img/mylogo.gif"));
       }
     });
    

    The body of the message is one of the parts of the multipart message (note the second parameter set to true on the constructor of MimeMessageHelper that sets the message to a multipart message).

    The line message.addInline("myLogo"... adds the image as another part of the multipart message.

    You can use .setText to set the body (HTML content) of the email message.

    You can refer to other parts of the multipart email (your image) by using the tag cid. Note how the img src attribute is src='cid:myLogo'. cid is the content id of the image, sent as one of the parts of the multipart message.

提交回复
热议问题