0

I'd like to make a call to Mailgun service with Play's WS api. Mailgun requires a API key sent for Authentication, and per their 'jersey' client example, they specify this API key as 'HTTPBasicAuthFilter' with the client, as below:

public static ClientResponse SendSimpleMessage() {
       Client client = Client.create();
       client.addFilter(new HTTPBasicAuthFilter("api",
                       "key-3ax6xnjp29jd6fds4gc373sgvjxteol0"));
       WebResource webResource =
               client.resource("https://api.mailgun.net/v2/samples.mailgun.org" +
                               "/messages");
       MultivaluedMapImpl formData = new MultivaluedMapImpl();
       formData.add("from", "Excited User <me@samples.mailgun.org>");
       formData.add("to", "bar@example.com");
       formData.add("to", "baz@example.com");
       formData.add("subject", "Hello");
       formData.add("text", "Testing some Mailgun awesomness!");
       return webResource.type(MediaType.APPLICATION_FORM_URLENCODED).
               post(ClientResponse.class, formData);
}

How can I do the same thing with Play's WS api?

Veera
  • 32,532
  • 36
  • 98
  • 137

2 Answers2

0

I figured it out, after poking around the WS class for a while. Here's what I did.

    public class MailHelper {

    public static Promise<WS.Response> send(EmailData emailData) {
        WSRequestHolder mailGun = WS.url("https://api.mailgun.net/v2/feedmerang.com/messages");
        mailGun.setAuth("api", "MAILGUN_API_KEY");
        mailGun.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        mailGun.setQueryParameter("from", emailData.from);
        mailGun.setQueryParameter("to", emailData.to);
        mailGun.setQueryParameter("subject", emailData.subject);
        mailGun.setQueryParameter("html", emailData.body);
        return mailGun.post("Sending Email");
    }
}
Veera
  • 32,532
  • 36
  • 98
  • 137
  • 1
    That code is definitely not thread safe, you will get very weird problems when two things try to make a request at once. Get rid of the static WSRequestHolder field, and move the code to create it and set the auth key into the send method, otherwise you're asking for trouble. – James Roper Mar 23 '14 at 05:34
  • What is this `APPLICATION_FORM_URLENCODED ` I am getting error there ! Thanks for the help... – Sagiruddin Mondal Aug 22 '14 at 18:42
0

Use WS withAuth:

WS.url(apiUrl).withAuth("api", apiKey, WSAuthScheme.BASIC).post(postMessage)
  • apiUrl is the URL you want to POST to

  • apiKey is the key from mailgun

  • postMessage is a Map of String to Seq of String. In Scala that is Map[String, Seq[String]] and looks like the following:

    val postMessage = Map("from" -> Seq(message.from), "to" -> Seq(message.to), "subject" -> Seq(message.subject), "text" -> Seq(message.text), "html" -> Seq(message.html.toString()))
    
Arthur
  • 1,332
  • 2
  • 19
  • 39