Skip to content

Instantly share code, notes, and snippets.

@adamldavis
Created November 1, 2012 21:17
Show Gist options
  • Select an option

  • Save adamldavis/3996601 to your computer and use it in GitHub Desktop.

Select an option

Save adamldavis/3996601 to your computer and use it in GitHub Desktop.
Using Mailgun with Groovy in Heroku
import org.apache.http.*
import org.apache.http.entity.*
import org.apache.http.client.*
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.params.*
import org.codehaus.groovy.grails.plugins.codecs.URLCodec
/** Uses MailGun to send emails. */
class EmailService {
static API_KEY = System.env.MAILGUN_API_KEY
def sendEmail(to, subject, text) {
final codec = URLCodec.newInstance()
Object.metaClass."encodeAsURL" = { -> codec.encode(delegate) }
Object.metaClass."decodeURL" = { -> codec.decode(delegate) }
def url = 'https://api.mailgun.net/v2/your-app.mailgun.org/messages'
def params = [from: "you@email.com", to: to, subject: subject, text: text]
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");
def list = []
params.each {k,v -> list << "${k}=${v.encodeAsURL()}" }
post.entity = new StringEntity(list.join('&'))
def response = httpclient.execute(post);
response
}
}
@chongivan

Copy link
Copy Markdown

import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.impl.auth.BasicScheme

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment