Sending Email in the Cloud is Easy With MailgunMailgun on OpenShiftSend E-mail - Archived

Mailgun on OpenShift

Sending and receiving e-mails in the cloud can be difficult, however there are tools and services that can help you handle such a task and relieve you of a lot of pain.

I am not affiliated with the service, nor is OpenShift or Red Hat. This blog post is not here to promote this particular service, but to give you an idea, what services you may use along OpenShift.

What is Mailgun?

Mailgun is “a set of powerful APIs that allow you to send, receive, track and store email effortlessly”. But what does that mean? To send or receive e-mails you need a SMTP server that handles the transport of e-mails among servers. On the other hand you need POP3 or IMAP server to access the e-mails received using SMTP server from other peers on the internet. That is a lot of things to do and set up, right?

Mailgun is running these servers for you, but on top of that it provides APIs to send and receive the e-mails. When you want to send an e-mail, you just do a HTTP request to the service and it handles the rest, the same but the opposite way it is in case of receiving. When an e-mail arrives, the service does a simple HTTP request to you application and you can handle the data as you want. No servers, no configuration, just our beloved HTTP protocol to send and receive e-mails, doesn’t sound awesome?

Mailgun has a free tier to let you started, just sign up here and you gen a free account that will be enough for us to start.

In this article I will be doing the demos using Ruby and a gem called Faraday (one of the many HTTP clients), but the same can be done using any other language – Python, Java, PHP, whatever.

Send E-mail

As I said before, sending an e-mail is just one HTTP request.

require 'faraday'
 
conn = Faraday.new(:url => 'https://api.mailgun.net/v2') do |faraday|
  faraday.request  :url_encoded
  faraday.response :logger
  faraday.adapter  Faraday.default_adapter
end
 
conn.basic_auth('api', '<you api>')
 
params = {
  :from => 'John Doe <john@doe.com>',
  :to => 'mr@president.com',
  :subject => 'Hello',
  :text => 'Testing some Mailgun from OpenShift!'
}
 
conn.post('<your domain>/messages', params)

The first block is configuration of the client library, we specify, the we want URL encoded request body, that the response should be logged to stdout and that underlying library to use to send the e-mail (default adapter is bundled with every Ruby). Also the library takes the base URL to use for requests.

Then we specify HTTP Basic authentication information. The username is constant and password is your API key, that can be found on the first page in the Mailgun Control Panel.

Parameters will be encoded as a HTTP request body on the last line, where we make the actual request to Mailgun’s API endpoint. The domain names you can use from your account are available also on the first page of Mailgun’s Control Panel.

You can do this on your local machine, in your web application on OpenShift or on the command line interface in OpenShift, it does not matter, it is gonna work everywhere. Of course more parameters are available, the whole documentation can be found here.

Receiving e-mails

Here it’s a bit more work, but still nothing complicated.

In the Control Panel go to the “Routes” tab and click “Create route”. There we specify how the route should behave

Priority = 0
Filter Expression = catch_all()
Actions = forward("<some url in your application>")
Description = Forward all my messages to this URL

With such a route once an e-mail comes to your mailbox (whatever@), it will be parsed and the URL specified in the Actions will be POST requested with the resulting data from the parsing.

A possible implementation using Sinatra framework may look like

require 'rubygems'
require 'bundler/setup'
 
Bundler.require(:default)
 
Mailer = Faraday.new(:url => 'https://api.mailgun.net/v2') do |faraday|
  faraday.request  :url_encoded
  faraday.adapter  Faraday.default_adapter
end
 
Mailer.basic_auth('api', '<you api key>')
 
MailerParams = {
  :from => 'John Doe <john@doe.com>',
  :to => 'mr@president.com',
  :subject => 'Some information',
}
 
class App < Sinatra::Base
 
  get '/' do
    Mailer.post('<your domain>/messages', MailerParams.merge({:text => params.inspect}))
  end
 
  post '/' do
    Mailer.post('<your domain>/messages', MailerParams.merge({:text => params.inspect}))
  end
 
end
 
run App

This is a simple extension to our previous example, that adds web interface for sending the messages and provides an endpoint to be contacted when an e-mail arrives, in such a case it send to pre-configured e-mail address all the data available in the request.

The source code is also available in a Github repository.

Testing the sample application

First of all sign up for OpenShift and set up you local machine with the client tools.

Now we can create an OpenShift application

rhc app create mailgun ruby-1.9

enter the directory with the application and fetch the source code from github

cd mailgun
git pull -s recursive -X theirs git://github.com/openshift-quickstart/mailgun-openshift-quickstart.git master

Configure the parameters in config.ru file and commit.

$EDITOR config.ru
git add .
git commit -m "Configuration"

The application is ready to be deployed, to do so, just push to OpenShift

git push origin master

and your application is ready to rock!

Open you browser and and navigate to the application URL, in my case it would be http://mailgun-mjelen.rhcloud.com and add some URL parameters to the path, in the end the URL may look similar to

http://mailgun-mjelen.rhcloud.com?hello=world

Once you open that URL, an e-mail should arrive to the mailbox specified in the application with content

{'hello' => 'world'}

To test the other way. Send an email to “whatever@<your domain>” and wait till another e-mail arrives containing the parsed original message – for this to work, you need to specify the application URL in the forward(“<your url>”).

Conclusion

Handling e-mails in cloud is not easy, but there are several services like Mailgun that may help you achieve simple deployment of e-mail based application without the need to touch SMTP or IMAP/POP3 servers. Best part is the whole web back-end can be deployed in a very simple way, and for free, on OpenShift.

What’s Next?

Categories
Ruby
Tags
, ,
Comments are closed.