How Ruby-based DNSimple uses Mailgun’s API to create & configure domains for email forwarding

Written by Mailgun Team

Categories: Customer Success

3 minute read time

This post is written by Anthoy Eden, founder and developer, at DNSimple. DNSimple is the hassle-free way to manage all of your domains in a single place without having to click through 10 screens of upsells to complete a simple purchase. In addition to registrar services, DNSimple offers a REST API for creating and managing domains and records. They also make it easy to receive email at your domain and forward to any other email account, like an email alias you have set up to handle support or billing emails, or an external email provider like Gmail.

At DNSimple we love DNS in an almost unhealthy way. What we don’t love though is managing mail servers. Earlier this year we decided to add email forwarding as one of the services we offer to our customers, and given our distaste in email server management we went looking for a provider with a nice API that we could easily integrate. Thanks to recommendations on Twitter we ended up finding and going with Mailgun and we have been thrilled with how easy it has been for us to integrate and maintain.

Programmatically creating and configuring domains

Our web application is developed using Ruby on Rails, so integrating Mailgun was a snap.

We use HTTParty, a nice little Ruby gem from John Nunemaker, to communicate with the Mailgun API. First we set up a class that is our client:

require 'httparty'

class Mailgun

  class MailgunError < StandardError

  include HTTParty

  base_uri ''
  basic_auth 'api', C_.mailgun_api_key


Once we have this class we can call through to the API to start our process of programmatically creating and configuring new custom domains for our customers to use for forwarding emails.

mailgun_domain_res = Mailgun.get("/domains/#{domain.unicode_name}")
if mailgun_domain_res.code != 200
  mailgun_domain_res ='/domains', :body => {:name => domain.unicode_name, :smtp_password => smtp_password})
  # if created then increment the count
  if mailgun_domain_res.code == 200
    raise "Failed to create domain in Mailgun"

In this case we first check to see if a domain exists in Mailgun. If it already exists then we can move onto the next step. If it does not exist then we create it by invoking a POST request to the /domains resource. We pass the name and an SMTP password. If the domain was successfully created then we increment the email forwarding count for the customer since we bill on a per domain basis. If this is the first time we create the domain then we also add MX records for sending automatically for our customers as well as the appropriate SPF record which increases deliverability.

Setting up email forwarding based on regex match

Next we set up the email forwarding that the customer requested (e.g. forward emails to to In Mailgun, this feature is called a “route” because it describes how to route a message. In our case we want to route based on a regular expression provided by the customer and forward the domain to the destination email address that they choose:

mailgun_route_res ="/routes", body: {
  description: "Email forwarding",
  expression: %Q(match_recipient('#{email_forward_attributes[:from]}')),
  action: %Q(forward('#{email_forward_attributes[:to]}'))

mailgun_route =
if mailgun_route_res.code != 200
  raise Mailgun::MailgunError, mailgun_route.message

If the route cannot be set up then we raise an error, otherwise we return the Mailgun route. Once we have a route we store the route_identifier in our database and that’s it!

If a customer decides to remove routes then we can simply delete them via the API:

mailgun_route_res = Mailgun.delete("/routes/#{email_forward.route_identifier}")

And if they have no more routes then we also remove the domain from the Mailgun system:

mailgun_domain_res = Mailgun.delete("/domains/#{domain.unicode_name}")


Compared to the pain and frustration of having to operate and maintain a growing mail storage and delivery system, Mailgun provides an extremely simple way to set up email for our customers, and we love them for that.

Modified on: March 13, 2019

Stay up-to-date with our blog & new email resources

We'll let you know when we add new email resources and blog posts. We promise not to spam you.