Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mailgun API: Sending Inline Image with Spring's RestTemplate

The goal is to send an email with inline image. Everything is working well, except the image is not appearing in the email.

My approach is based on this Jersey-example of Mailgun's User Guide.

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", "[email protected]");
   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's RestTemplate.

This is what I've got 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 remaining part is to put the *.png file into the map. Not sure how to do that. Have tried reading all its bytes via ServletContextResource#getInputStream, but without success: Image is not appearing in the resulting e-mail.

Am I missing something here?

like image 955
Håvard Geithus Avatar asked Feb 27 '16 17:02

Håvard Geithus


1 Answers

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

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

For Mailgun you need to use the map-key "inline". Also, the ServletContextResource has a method getFilename(), which is used to resolve against the image tag. Thus, the image tag should have the following content id:

<img src="cid:email-banner.png"/>
like image 69
Håvard Geithus Avatar answered Sep 27 '22 23:09

Håvard Geithus