Mailgun for Rails Application Mailgun for Rails Application heroku heroku

Mailgun for Rails Application


Mailgun is no different from Sendgrid or Mandrill, so when looking for some guidance, you can also consider these solutions. Hands down the best guide for your use case is Sending Emails in Rails Applications. You can also choose from the existing gems to Mailgun API Official gem or ActiveRecord integration.

The way I have already implemented is to setup the areas, add the gemfile and then setup the background processor through Active Job. I have not yet setup the background processor due to being unsure if this is the best way.

Yes, this is the correct way how to set it up. Prior to Rails 4.2, and I believe most of those who have coded without the existence of ActiveJob still prefer things like dj, sidekiq or resque and they are really popular and can be found in almost every Rails app. You can use them with the interface of ActiveJob. Nevertheless, to concept is the same.

To give you an idea about the missing part of code, you can do something like this (from the 1st link)

class ExampleMailer < ActionMailer::Base  def sample_email(user)    @user = user    mg_client = Mailgun::Client.new ENV['api_key']    message_params = {:from    => ENV['gmail_username'],                      :to      => @user.email,                      :subject => 'Sample Mail using Mailgun API',                      :text    => 'This mail is sent using Mailgun API via mailgun-ruby'}    mg_client.send_message ENV['domain'], message_params  endend

Side note: I was also told along the way "Don't trigger the email sending from an ActiveRecord callback - Do it from the controller." I wrote that down to refer to when the time came for it and here I am =P Would you agree with that statement?

I would definitely agree with the statement. One thing is that chaining everything to the ActiveRecord callbacks might seem really practical at first sight, but then, as the application grows, you will see yourself putting in conditional statements or using things like state machines to be covered up. The case behind is that you might create records in your application from multiple sources (user registration, admin import etc.) and not in every case you would like the email to be sent. Furthermore for me and to new team members it is more practical to see it directly in the controller code, rather then going through the models' callbacks. In the end this can be considered also as a personal preference.

If you are using Heroku - then take a look at this Delayed Job guide. On Heroku, you will have to run these background processes in the separate workers (which are not free), for some cost effective solutions take a loot at Running delayed jobs on Heroku for free.