I’m trying to integrate MailGun with Devise authentication in my Rails app using the mailgun-ruby gem. I keep getting an error that says the MailGun constant is not initialized.
In my production.rb file, I added the MailGun configuration:
Then I created a custom mailer that extends Devise’s mailer:
class UserMailer < Devise::Mailer
require 'mailgun-ruby'
helper :application
include Devise::Controllers::UrlHelpers
default template_path: 'users/mailer'
def confirmation_instructions(user, token, opts={})
mailgun_client = MailGun::Client.new
email_params = {
from: "[email protected]",
to: user.email,
subject: "Confirm your email address"
}
mailgun_client.send_message email_params
super
end
end
I commented out the mailer configuration in devise.rb but Rails seems to think MailGun should be a constant inside UserMailer. What could be causing this issue?
you’re overthinking it. set delivery method to mailgun in production.rb and rails does the rest automatically. ditch all that manual mailgun client code from your mailer - just use regular mail(to: user.email, subject: "whatever") syntax. the mailgun config you added is enough.
The issue is with the constant name - it should be Mailgun::Client not MailGun::Client. The mailgun-ruby gem uses Mailgun (single word) as the module name, not MailGun with camelCase. I ran into this exact same problem when I first started using the gem. You’re also mixing approaches here. If you’ve already set config.action_mailer.delivery_method = :mailgun in your production.rb, don’t manually instantiate the Mailgun client in your mailer. ActionMailer will handle the delivery through Mailgun automatically. Just change your confirmation_instructions method to use the standard Rails mailer pattern and let ActionMailer do the work. Drop the manual client stuff and use the mail() method like any other Rails mailer.
I hit the same issues recently with this exact setup. You’re mixing Rails ActionMailer integration with manual Mailgun client calls, and that’s what’s breaking everything. When you set config.action_mailer.delivery_method = :mailgun in production.rb, Rails handles all the delivery stuff automatically. Your UserMailer should just build the email content - that’s it. Rip out the mailgun_client instantiation and send_message call from your confirmation_instructions method completely. Just use the standard mail() helper method instead. The Mailgun integration catches it automatically when ActionMailer tries to send. Also double-check that your ENV variables are actually loading in production - missing credentials usually show up as constant errors like this.