Mailgun API: sending inline image using Spring RestTemplate

The goal is to send an email with an embedded image. Everything works well, except that the image does not appear in the letter.

My approach is based on this Jersey Mailgun User Guide example .

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); } 

However, I need to use Spring RestTemplate.

This is what I have so far:

 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); 

The rest is to put the *.png file on the map. Not sure how to do this. We tried to read all my bytes through ServletContextResource # getInputStream, but to no avail: the image does not appear in the received email.

Am I missing something?

+5
source share
1 answer

This turned out to be the case when everything was set up correctly, but only a small detail prevented him from working.

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

For Mailgun you need to use the "inline" key card. In addition, ServletContextResource has a getFilename() method, which is used to resolve against the image tag. Thus, the image tag must have the following content identifier:

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

Source: https://habr.com/ru/post/1244020/


All Articles