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?