Groovy Mailgun in Heroku

I had some problems using Mailgun from Groovy. Mailgun’s SMTP api didn’t work for me, so I used their REST api. Here are the details…

First you need to add the encodeAsURL method to Object’s metaClass. You’ll use this later for encoding the parameters.

final codec = URLCodec.newInstance()

Object.metaClass.”encodeAsURL” = { -> codec.encode(delegate) }

Then define your API url and parameters:

def url = ‘’ 

def params = [from: “”, to: to, subject: subject, text: text]

Next, create the DefaultHttpClient and HttpPost with credentials and headers:

def httpclient = new DefaultHttpClient()

def post = new HttpPost(url);

def creds = new UsernamePasswordCredentials(‘api’, API_KEY)

post.addHeader(BasicScheme.authenticate(creds, “US-ASCII”, false));

post.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);

Lastly, encode the parameters, join them, and put them in the post.

def list = []

params.each {k,v -> list « “${k}=${v.encodeAsURL()}” }

post.entity = new StringEntity(list.join(‘&’))


That’s it, you’re done!

Here’s the full gist of EmailService.