Search code examples
ruby-on-railsherokumailgun

Using MailGun for ruby on rails application on Heroku


I am trying to use MailGun to send emails in my RubyonRails application which is hosted on heroku.

I added the MailGun addon to my heroku application. I updated my config/environments/production.rb as below:

config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :port           => ENV['MAILGUN_SMTP_PORT'],
    :address        => ENV['MAILGUN_SMTP_SERVER'],
    :user_name      => ENV['MAILGUN_SMTP_LOGIN'],
    :password       => ENV['MAILGUN_SMTP_PASSWORD'],
    :domain         => 'mydomain.herokuapp.com', #mydomain actually contains the realvalue
    :authentication => :plain,
  }

I created a file in app/mailers directory:

class ApplicationMailer < ActionMailer::Base
  default from: "[email protected]"

  def notify_user(user)
    puts "Going to send email!! to"
    puts user
    mail(to: user, subject: "Welcome!")
  end
end

In my application_controller.rb

I have a function:

def notify_people()
    puts "Notify people!"
    ApplicationMailer.notify_user("[email protected]")
    puts "over"
end

From one of my other controllers I call notify_people. However in my heroku logs, Notify people! is being printed, and nothing after that. I am not able to understand why it is not able to called notify_user.

My notify_user function is:

class ApplicationMailer < ActionMailer::Base default from: "[email protected]" #layout 'mailer' def notify_user(user) puts "Going to send email!! to" puts user mail(to: user, subject: "Welcome!") puts "Done sending mail!" return end end


Solution

  • Call the mailer with .deliver_later:

    ApplicationMailer.notify_user("[email protected]").deliver_later
    

    also, make sure the ENV variables are set on Heroku using details from your Mailgun account.

    EDIT: You're probably getting an exception from the call to ApplicationMailer. Ideally you should troubleshoot that in development, but if needed you can add: config.action_mailer.raise_delivery_errors = true to production.rb to get visibility into what's happening.

    Tangentially, instead of print statements take a look at debuggers like byebug and pry-byebug. They can save you a lot of time troubleshooting.