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 = ‘https://api.mailgun.net/v2/your-app.mailgun.org/messages’ 

def params = [from: “you@email.com”, 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(‘&’))

httpclient.execute(post);

That’s it, you’re done!

Here’s the full gist of EmailService.