【发布时间】: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