我正在使用spring samples发送内联图片。它有效但gmail也将图像显示为附件。如何避免呢?
代码非常简单。
public class Email {
public static MimeMessagePreparator getContentAsInlineResourceMessagePreparator(final String to) {
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setSubject("Email with inline image");
helper.setFrom("fake@yourshop.com");
helper.setTo(to);
String content = "Dear pedrofb...";
helper.setText("<html><body><p>" + content + "</p><img src='cid:company-logo'></body></html>", true);
helper.addInline("company-logo", new ClassPathResource("logo.png"));
}
};
return preparator;
}
public final static void main (String argv[]){
//Basic SMTP configuration
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
MimeMessagePreparator preparator = getContentAsInlineResourceMessagePreparator("myemail@gmail.com");
mailSender.send(preparator);
}
}
我的问题与How to stop embedded images in email being displayed as attachments by GMail?类似,但答案很老,并没有说明如何正确配置弹簧。我不想自己构建消息部分和标题
中发布原始邮件答案 0 :(得分:11)
问题在于MimeType
确定
png
扩展程序被视为image/x-png
而不是image/png
,这会导致Gmail出现问题。这已在5.X
中修复/更改,也可能在某些4.X
更高版本中(我不确定)。但修复很容易。变化
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
到
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8") {
@Override
public void addInline(String contentId, Resource resource) throws MessagingException {
Assert.notNull(resource, "Resource must not be null");
String contentType = this.getFileTypeMap().getContentType(resource.getFilename());
contentType = contentType.replace("x-png", "png");
this.addInline(contentId, resource, contentType);
}
};
它会覆盖MimeType
到image/png
答案 1 :(得分:0)
我已经执行了你的代码。它工作得很好:我在gmail中打开生成的电子邮件,我看到了内嵌图片,但我看不到任何附件! 这可能是由于库版本?我使用了5.0.5.RELEASE。
如果这不是解决方案,我想您可能在SmtpServer.toJavaMailSender()或Gmail设置中有一些不常见的属性。