Created
November 1, 2012 21:17
-
-
Save adamldavis/3996601 to your computer and use it in GitHub Desktop.
Using Mailgun with Groovy in Heroku
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.impl.auth.BasicScheme