Best way to configure a Rails Mailer to ignore blank emails

I’m refactoring some old code and there are numerous checks here and there to not send an email if the order.email is blank.

Can’t that be put into the Mailer? I used this, below, but I still get an SMTP error when a blank email comes into the mailer.

class OrderMailer < ApplicationMailer
  after_action :ignore_blank_emails
            
  def sample_message(order)
  @order = order
    mail
  end
 
  private
 
    def ignore_blank_emails
      if @order && @order.email.blank?
        mail.perform_deliveries = false
      end
    end

end

perform_deliveries is a configuration method, so it’s probably not possible to use it in this way.

This should work:

  def sample_message(order)
    mail unless order.email.blank?
  end

But I would aim to restructure the other code so that the mailer is only called when needed.

1 Like

I would do the same.