Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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()))
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top