Я пытаюсь отправить электронное письмо с встроенным изображением с помощью ThymeLeaf и Spring, но пока ничего не получилось. Письмо отправляется, но встроенное изображение не отображается в письме.Как отправить электронную почту со встроенным изображением с помощью ThymeLeaf
Проект не веб-(не веб-сайт), но на рабочем столе автономно, не мобильный
Это, как я получить файл изображения:
URL url = getClass().getResource("/LawFirmAdvisoryGroup.jpg");
File file = new File(url.getPath());
MultipartFile multipartFile = new MockMultipartFile(file.getName(),
file.getName(), "image/jpeg", IOUtils.toByteArray(input));
Мой класс обслуживания:
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
public void sendMailWithInline(final String recipientName, final String recipientEmail, final MultipartFile image, final byte[] imageBytes)
throws MessagingException {
final Context ctx = new Context();
ctx.setVariable("imageResourceName", image.getName()); // so that we can reference it from HTML
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message
= new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setSubject("Inline Image");
message.setFrom("[email protected]");
message.setTo(recipientEmail);
// Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
message.addInline(image.getName(), imageSource, image.getContentType());
final String htmlContent = this.templateEngine.process("left_sidebar.html", ctx);
message.setText(htmlContent, true);
this.mailSender.send(mimeMessage);
}
HTML:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:remove="all">Email with inline image</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>
<img src="LawFirmAdvisoryGroup.jpg" th:src="'cid:' + ${imageResourceName}" />
</p>
</body>
</html>
«_so далеко не success_ ". Вы действительно должны пытаться быть более описательными в том, что происходит, а не просто говорить «это не работает». – csmckelvey
@Takendarkk Я редактировал вопрос. Письмо отправляется, но встроенное изображение не отображается в письме. –
@ Program-Me-Rev, вы решили его? –