Skip to content

Using Postmark with Devise gem

Patrick Graham edited this page Aug 5, 2020 · 3 revisions

Tested with Rails 6.0.3.2 and Devise 4.7.2

Sending Devise's transactional emails with Rails templates

In order to send the default Devise's transactional emails with Postmark, you only need to configure the mailer_sender option in config/initializers/devise.rb:

  # ...

  # ==> Mailer Configuration
  # Configure the e-mail address which will be shown in Devise::Mailer,
  # note that it will be overwritten if you use your own mailer class
  # with default "from" parameter.
  config.mailer_sender = '<YOUR SENDER SIGNATURE EMAIL ADDRESS>'

  # ...

You may also set config.action_mailer.raise_delivery_errors to true in your application configuration - it can help with debugging your configuration issues.

Sending Devise's transactional emails with Postmark templates

If you want to use Postmark templates for Devise's emails you will need to create a custom mailer that inherits from Devise::Mailer and override the required actions:

# app/mailers/user_mailer.rb
class UserMailer < Devise::Mailer
  include PostmarkRails::TemplatedMailerMixin
  include Devise::Controllers::UrlHelpers
  default from: '<YOUR SENDER SIGNATURE EMAIL ADDRESS>'

  # Override Devise's action(s). By convention we will try to send this email using a template with an alias that
  # matches the action name. Such template must exist in the Postmark server associated with this mailer. In this case
  # the expected alias is: "reset_password_instructions".
  # You can also set the template alias explicitly: `mail to: record.email, postmark_template_alias: "my-reset-pass"`
  def reset_password_instructions(record, token, opts = {})
    self.template_model = {
      action_url: edit_password_url(record, reset_password_token: token),
      user_email: record.email,
      # ... etc.
    }

    mail to: record.email
  end

  def confirmation_instructions(record, token, opts = {})
    # ...
  end

  # ... other actions
end

Once you have the custom mailer you need to tell Devise to use it. Open config/initializers/devise.rb and set the mailer option:

  # ...

  # Configure the class responsible to send e-mails.
  config.mailer = 'UserMailer'

  # ...

With that you should be all set!


Huge thanks to Shawn Wilson for the initial draft of this page.