mac下图片无法直接显示,显示为附件
- 修改前代码摘要
//设置utf-8或GBK编码,否则邮件会有乱码
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, 3,
mailEncoding);
ClassPathResource resource = new ClassPathResource("img/logo.v3.png");
messageHelper.addInline(file.getContentId(),file.getResource());
此是图片在mac emal中显示为附件,在outlook中正常
- 修改后代码摘要
//附件
DataSource dataSource = new DataSource() {
@Override
public InputStream getInputStream() throws IOException {
return file.getResource().getInputStream();
}
@Override
public OutputStream getOutputStream() {
throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
}
@Override
public String getContentType() {
return contentType;
}
@Override
public String getName() {
return "inline";
}
};
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setHeader("Content-Type", contentType);
mimeBodyPart.setDisposition("inline");
mimeBodyPart.setHeader("Content-ID", "<" + file.getContentId() + ">");
mimeBodyPart.setFileName(file.getResource().getFilename());
mimeBodyPart.setDataHandler(new DataHandler(dataSource));
messageHelper.getMimeMultipart().addBodyPart(mimeBodyPart);
此时mac email中图片显示正常
3. 原因分析
MimeMessageHelper 的addInline没有指定文件名
mimeBodyPart.setFileName(file.getResource().getFilename());
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
Assert.notNull(contentId, "Content ID must not be null");
Assert.notNull(dataSource, "DataSource must not be null");
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDisposition("inline");
mimeBodyPart.setHeader("Content-ID", "<" + contentId + ">");
mimeBodyPart.setDataHandler(new DataHandler(dataSource));
this.getMimeMultipart().addBodyPart(mimeBodyPart);
}```