电子邮件中的内嵌图像不适用于MacOS电子邮件

时间:2017-02-08 15:07:56

标签: java image email spring-boot

我正在使用spring boot从java发送HTML电子邮件。电子邮件包括我们公司的图像标志签名。它工作得很好f.e.在gmail上。但是在MacOS应用程序电子邮件中,徽标是作为附件发送的,并且没有内联。

代码的非相关部分由...替换

final Locale locale = ...;
final MimeMessage mail = javaMailSender.createMimeMessage();
MimeMessageHelper helper;
try {
    helper = new MimeMessageHelper(mail, true, "UTF-8");
    helper.setTo(...);
    helper.setCc(...);
    helper.setBcc(...);
    helper.setFrom(...);

    final String htmlContent = templateEngine.process(..., new Context(locale, ...));
    helper.setText(htmlContent, true);
    helper.addInline("myImg", new ClassPathResource(".../myImg.png"));
} catch (UnsupportedEncodingException | MessagingException e) {
    throw new MailSendException(..., e);
}
javaMailSender.send(mail);

HTML由thymeleaf生成并且遵循:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
...
<img src=".../myImg.png" th:src="'cid:' + ${'myImg'}" />

</body>
</html>

2 个答案:

答案 0 :(得分:1)

查看此扩展程序Spring Boot Email Tools的代码,您可以找到更好的方法来创建电子邮件。

就个人而言,如果您直接使用它通过EmailService bean发送电子邮件,我认为您可以节省一些时间。从文档(该示例基于Freemarker模板引擎):

@Autowired
public EmailService emailService;

public void sendEmailWithTemplating(){
   Arrays.asList(new Cospirator("cassius@sic-semper.tyrannis", "Gaius Cassius Longinus"),
            new Cospirator("brutus@sic-semper.tyrannis", "Marcus Iunius Brutus Caepio"))
        .stream.forEach(tyrannicida -> {
       final Email email = DefaultEmail.builder()
            .from(new InternetAddress("divus.iulius@mala-tempora.currunt", "Gaius Iulius Caesar"))
            .to(Lists.newArrayList(new InternetAddress(tyrannicida.getEmail(), tyrannicida.getName())))
            .subject("Idus Martii")
            .body("")//Empty body
            .encoding(Charset.forName("UTF-8")).build();
        //Defining the model object for the given Freemarker template
        final Map<String, Object> modelObject = new HashMap<>();
        modelObject.put("tyrannicida", tyrannicida.getName());

       emailService.send(email, "idus_martii.ftl", modelObject);
   };
}

private static class Cospirator {
  private String email;
  private String name;
  public Cospirator(final String email, final String name){
    this.email = email;
    this.name = name;
  }

  //getters
}

您需要的依赖项是

<dependency>
    <groupId>it.ozimov</groupId>
    <artifactId>spring-boot-email-core</artifactId>
    <version>0.4.0</version>
</dependency>
<dependency>
    <groupId>it.ozimov</groupId>
    <artifactId>spring-boot-thymeleaf-email</artifactId>
    <version>0.4.0</version>
</dependency>

很方便,不是吗?

答案 1 :(得分:-2)

您是否尝试将图像加载到服务器然后发送?由于图像具有服务器尝试作为附件发送的相对路径。

干杯