Receive Emails with mailgun

mailgun is a great service that handles the difficult parts of handling emails for developers. One of the features they offer is the ability to POST to an HTTP endpoint upon receiving an email. We’ll use this feature to have mailgun send a POST request to a plumber API when an email arrives to a certain email address. mailgun has a very generous free tier, so you can replicate this exercise without spending a dime.

Mailgun Configuration

After registering for a mailgun account, you’ll either need to use their sandbox, or configure a (sub)domain name to be hosted by mailgun. In my case, I setup plumber.tres.tl to have its email hosted by mailgun. You could just as easily use mailgun.myorg.com if you don’t want to disrupt email hosting on your production domain.

Once you have a domain setup, you just add a route that tells mailgun what to do with your email. In my case, I said that it should listen for emails sent to mailgun@plumber.tres.tl and, when one comes in, convert it to an HTTP POST request and send it to http://plumber.tres.tl/mailgun/mail.

Plumber API

This example will auto-refresh every 3 seconds with the latest emails the API has received. Try sending an email to mailgun@plumber.tres.tl to see the API at work.

GET /tail

GET https://plumber.tres.tl/mailgun/tail
Time Subject

mailgun.R

emails <- data.frame(from=character(0), time=character(0), subject=character(0), stringsAsFactors = FALSE)

#* @post /mail
function(from, subject){
  emails <<- rbind(emails, data.frame(from=from, time=date(), subject=subject, stringsAsFactors=FALSE))
  TRUE
}

#* @get /tail
function(){
  tail(emails[,-1], n=5)
}