2016-02-27 56 views
5

目標是發送帶內嵌圖像的電子郵件。一切運行良好,除非圖像沒有出現在電子郵件中。Mailgun API:使用Spring的RestTemplate發送內嵌圖像

我的方法是基於這個澤西島的例子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 <[email protected]_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); 
} 

但是,我需要使用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讀取所有字節,但沒有成功:圖像未出現在生成的電子郵件中。

我在這裏錯過了什麼嗎?

回答

3

事實證明,這一切都是正確設置的,但只有一個小細節阻止它的工作。

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

對於Mailgun,您需要使用map-key「inline」。此外,ServletContextResource有一個方法getFilename(),用於解決圖像標記。因此,圖像標籤應該具有以下內容ID:

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