quick tip: how to explicitly assign a ActiveJob to an ActionMailer

Jumpstart OTB uses Rails' default mailer behavior, which is to magically, behind the scenes, use your default ActiveJob queue to send email if set via deliver_later.

Works, but unsuitable for production apps IMO.

There's some pretty good reasons to override that and explicitly define a Job to handle the email, such as being able to specify a different queuing backend (I like delayed_job), and being able to turn off automatic retries (pretty important for emails to prevent blasting a zillion copies in case of a smtp server handshake timeout).

The way to configure a mailer to use an explicit Job is simple, but as-yet still undocumented in the Rails ActionMailer guide:

class AccountInvitationsMailer < ApplicationMailer
  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.account_invitations_mailer.invite.subject
  #
  self.delivery_job = SendUserInvitationToAccountJob  #### THIS LINE HERE ####

  def invite
    @account_invitation = params[:account_invitation]
    @account = @account_invitation.account
    @invited_by = @account_invitation.invited_by
    @service_name = Jumpstart.config.application_name

    name = @account_invitation.name
    email = @account_invitation.email

    mail(
      to: "#{name} <#{email}>",
      from: "#{@invited_by.name} <#{Jumpstart.config.support_email}>",
      subject: t(".subject", 
        inviter: @invited_by.name, 
        account: @account.name, 
        service_name: @service_name)
    )
  end
end

that line lets you define a specific Job, with a specific configuration, and even a different queuing backend, rather than using the same default queuing backend as you re using for Turbo, Stimulus, etc.

Notifications
You’re not receiving notifications from this thread.
Subscribe
© 2021 GoRails, LLC