【发布时间】:2015-08-21 12:23:06
【问题描述】:
我正在尝试使用 ThymeLeaf 和 Spring 发送带有内联图像的电子邮件,但到目前为止还没有成功。电子邮件已发送,但内联图像不会显示在电子邮件中。
该项目不是基于网络的(不是网站),而是一个独立的桌面,而不是移动
这是我获取图像文件的方式:
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("XXXX@yahoo.com");
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>
【问题讨论】:
-
"到目前为止没有成功" 你真的应该尝试对正在发生的事情进行更多描述,而不是仅仅说“它不起作用”。
-
@Takendarkk 我确实编辑了这个问题。电子邮件已发送,但内联图像不会显示在电子邮件中。
-
@Program-Me-Rev,你解决了吗?
-
@Program-Me-Rev 提供的以下解决方案是否解决了这个问题?我也面临同样的问题。
-
@Program-Me-Rev 我可以知道输入是什么吗?