【问题标题】:Mailgun API: Sending Inline Image with Spring's RestTemplateMailgun API:使用 Spring 的 RestTemplate 发送内联图像
【发布时间】:2016-02-27 17:54:53
【问题描述】:

目标是发送带有内嵌图像的电子邮件。一切都运行良好,除了图像没有出现在电子邮件中。

我的方法基于Mailgun's User Guide 的这个 Jersey 示例。

public static ClientResponse SendInlineImage() {
   Client client = Client.create();
   client.addFilter(new HTTPBasicAuthFilter("api",
                   "YOUR_API_KEY"));
   WebResource webResource =
           client.resource("https://api.mailgun.net/v3/YOUR_DOMAIN_NAME" +
                           "/messages");
   FormDataMultiPart form = new FormDataMultiPart();
   form.field("from", "Excited User <YOU@YOUR_DOMAIN_NAME>");
   form.field("to", "baz@example.com");
   form.field("subject", "Hello");
   form.field("text", "Testing some Mailgun awesomness!");
   form.field("html", "<html>Inline image here: <img src=\"cid:test.jpg\"></html>");
   File jpgFile = new File("files/test.jpg");
   form.bodyPart(new FileDataBodyPart("inline",jpgFile,
                   MediaType.APPLICATION_OCTET_STREAM_TYPE));
   return webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).
           post(ClientResponse.class, form);
}

但是,我需要使用 Spring 的 RestTemplate。

这是我目前所得到的:

RestTemplate template = new RestTemplate();

MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
// ... put all strings in map (from, to, subject, html)

HttpHeaders headers = new HttpHeaders();
// ... put auth credentials on header, and content type multipart/form-data

template.exchange(MAILGUN_API_BASE_URL + "/messages", HttpMethod.POST,
        new HttpEntity<>(map, headers), String.class);

剩下的部分是将*.png文件放入地图中。不知道该怎么做。已尝试通过 ServletContextResource#getInputStream 读取其所有字节,但没有成功:图像未出现在生成的电子邮件中。

我在这里遗漏了什么吗?

【问题讨论】:

    标签: java spring multipartform-data resttemplate mailgun


    【解决方案1】:

    事实证明,一切都设置正确,但只有一个小细节使其无法正常工作。

    map.add("inline", new ServletContextResource(this.servletContext,   
        "/resources/images/email-banner.png"));
    

    对于 Mailgun,您需要使用映射键“内联”。此外,ServletContextResource 有一个方法getFilename(),用于解析图像标签。因此,图像标签应具有以下内容 id:

    <img src="cid:email-banner.png"/>
    

    【讨论】:

      猜你喜欢
      • 2014-11-27
      • 2014-10-02
      • 2016-12-10
      • 2013-02-24
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多