At bandzoogle we wanted to use Mailgun as our mail provider for sending emails. Mailgun offers 2 interfaces: SMTP and an HTTP api. If you want to use mailgun in a Rails app via Action Mailer, the only alternative you can use out of the box is the Action Mailer SMTP adapter.

The SMTP approach works great unless you want to send mail in batches. For sending emails in batches with mailgun, you must use recipient variables, which are substitutions you want to make based on each recipient. They indicate to mailgun that each message must be individualized and they prevent the to field from containing the full list of recipients.

Providing these recipient variables via SMTP requires you to use a very specific MIME format for wrapping the message. Doing that with Rails is not trivial, as it requires you to use the internal objects of Action Mailer to form the custom MIME. I didn’t manage to make it work, even replicating the documented format, and Mailgun support couldn’t help me with this approach in Rails.

So I decided to go with the HTTP API, which is much better documented and much easier to use for setting recipient variables. I created an adapter named mailgun_rails:

  • It lets you use plain Action Mailer for sending emails with Mailgun.
  • It supports Mailgun specific features like recipient variables or custom variables that will be received via Mailgun webhooks.
  • It supports sending HTML messages, TEXT messages or both depending of how the Action Mailer message is composed.

An example of usage:

email = mail from: 'jorge@email.com',
             to: ['user_1@email.com', 'user_2@email.com'],
             subject: 'Hey, this is a test email'

email.mailgun_variables = {name_1: :value_1, :name_2 => value_2}
email.mailgun_recipient_variables = {'user_1@email.com': {id: 1}, 'user_2@email.com': {id: 2}}

You can read more about the adapter on github.