I’m trying to integrate Mailgun with my Rails app that uses Devise for user authentication. I’ve set up the mailgun-ruby gem and configured my production environment, but I keep getting an error when my custom mailer tries to use the Mailgun client.
class CustomMailer < Devise::Mailer
require 'mailgun-ruby'
helper :application
include Devise::Controllers::UrlHelpers
default template_path: 'users/mailer'
def confirmation_instructions(record, token, opts={})
mailgun_client = MailGun::Client.new
email_params = {
from: "[email protected]",
to: record.email,
subject: "Confirm your email address"
}
mailgun_client.send_message email_params
super
end
end
The weird thing is that Rails seems to be looking for MailGun as a constant inside my CustomMailer class instead of the gem’s namespace. I get an “uninitialized constant CustomMailer::MailGun” error. What could be causing this issue?
you’re mixing two approaches - pick either rails’ built-in mailgun integration OR the direct client, not both. since you’ve got delivery_method = :mailgun set up, ditch the manual client code and let devise do its thing. also double-check your gemfile has the mailgun gem properly required - that constant error usually means gems aren’t loading right.
The namespace issue is coming from how you’re setting up the Mailgun client. You’re overcomplicating this - you don’t need both Rails’ built-in mailgun delivery method AND the direct gem API at the same time. Since you’ve already got delivery_method = :mailgun in your production config, Rails will automatically send emails through Mailgun when you use regular ActionMailer methods. Just delete the manual mailgun_client setup from your confirmation_instructions method and customize the email content using normal Rails mailer patterns. The super call will handle delivery through your existing Mailgun setup. If you really need direct API access for something specific, put that in a separate service class instead of mixing it with Devise’s mailer inheritance.
Had the exact same issue with mailgun-ruby last year. Your class name is wrong - you’re using MailGun::Client.new but it should be Mailgun::Client.new (lowercase ‘g’). The gem uses Mailgun, not MailGun. But here’s the bigger problem: you don’t need to manually create the Mailgun client at all. You’ve already set Rails to use mailgun in your production config, so Rails handles the sending automatically when you call your mailer methods. Just simplify your custom mailer to override the template and styling. Let Devise handle delivery through your existing Mailgun settings. The manual client stuff is just adding complexity and conflicts with Rails’ mail system.