Search code examples
ruby-on-railsdevisemailgun

MailGun + Devise + Rails = "uninitialized constant MyMailer::MailGun"?


I am using Devise for authentication and the mailgun-ruby gem for sending email, and I am having difficulty figuring out how to make Devise's default mailer class work with Mailgun. Per the mailgun doc, I have configured my production.rb file to use mailgun settings:

config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
 api_key: ENV['MAILGUN_API_KEY'],
 domain: 'mail.mywebsite.com'
}

And then in my mailer class, I require the gem and instantiate a Mailgun::Client object.

class MyMailer < Devise::Mailer
  require 'mailgun-ruby'
  helper :application
  include Devise::Controllers::UrlHelpers
  default template_path: 'users/mailer'

 def confirmation_instructions(record, token, opts={})
  mg_client = MailGun::Client.new
  message_params = {
   from: "me@mywebsite.com",
   to: record.email,
   subject: "Please confirm your account"
  }

  mg_client.send_message message_params

  super
 end
end

I commented out the config.mailer = 'MyMailer' line in the devise.rb initializer, but for some reason, Rails is looking for MailGun as a subclass of MyMailer. Why is this? The error is in the title - uninitialized constant MyMailer::MailGun.


Solution

  • Looks like you have a spelling in your code

    mg_client = MailGun::Client.new
    

    should be

    mg_client = Mailgun::Client.new