-
Notifications
You must be signed in to change notification settings - Fork 5.5k
How To: Use custom mailer
jmarceli edited this page Apr 3, 2015
·
27 revisions
To use a custom mailer, create a class that extends Devise::Mailer
, like this:
class MyMailer < Devise::Mailer
helper :application # gives access to all helpers defined within `application_helper`.
include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
default template_path: 'devise/mailer' # to make sure that your mailer uses the devise views
end
Then, in your config/initializers/devise.rb
, set config.mailer
to "MyMailer"
.
You may now use your MyMailer
in the same way as any other mailer. In case you want to override specific mails to add extra headers, you can do so by simply overriding the method and calling super
after (triggering Devise's default behavior). For instance, we can add a new header for the confirmation_instructions e-mail as follow:
def confirmation_instructions(record, token, opts={})
headers["Custom-header"] = "Bar"
super
end
You can also override any of the basic headers (from, reply_to, etc) by manually setting the options hash:
def confirmation_instructions(record, token, opts={})
headers["Custom-header"] = "Bar"
opts[:from] = '[email protected]'
opts[:reply_to] = '[email protected]'
super
end
In order to get preview:
# test/mailers/previews/my_mailer_preview.rb
# Preview all emails at http://localhost:3000/rails/mailers/my_mailer
class MyMailerPreview < ActionMailer::Preview
def confirmation_instructions
MyMailer.confirmation_instructions(User.first, "faketoken", {})
end
def reset_password_instructions
MyMailer.reset_password_instructions(User.first, "faketoken", {})
end
def unlock_instructions
MyMailer.unlock_instructions(User.first, "faketoken", {})
end
end