Forum: Ruby on Rails ActionMailer cancel send from one of deliver_* methods

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D4e855a28dbcc327042084be99f6147b?d=identicon&s=25 surge (Guest)
on 2007-06-19 04:17
(Received via mailing list)
Seems like executing a return in one of the deliver_* methods of
ActionMailer doesn't cancel the delivery. The template is still read
right after the return method has been executed and because all
variables in the template are empty, all kinds of errors occur.

I need to validate the email (and test whether it actually exists)
before a delivery is made and I'm trying to put all that logic inside
the delivery methods themselves, but no luck.

Anybody know of a solution?
4a551074ddba4460f95d011c47190d0e?d=identicon&s=25 Henrik --- (malesca)
on 2008-11-05 20:23
surge wrote:
> Seems like executing a return in one of the deliver_* methods of
> ActionMailer doesn't cancel the delivery. The template is still read
> right after the return method has been executed and because all
> variables in the template are empty, all kinds of errors occur.
>
> I need to validate the email (and test whether it actually exists)
> before a delivery is made and I'm trying to put all that logic inside
> the delivery methods themselves, but no luck.
>
> Anybody know of a solution?

I needed this myself just now, and found this thread (on Ruby Forum), so
I figured I'd post my solution here for others to find, even though the
question was well over a year ago:

In my ApplicationMailer that I inherit all others mailers from, I do
this:

  # Allow cancelling mails from within a mailer by doing "raise
NotSendingMail".
  class NotSendingMail < StandardError; end
  def self.method_missing(*args)
    super
  rescue NotSendingMail => e
    RAILS_DEFAULT_LOGGER.info("Not mailing! #{e}")
  end

Should be pretty self-explanatory.

I suppose one could use throw/catch instead of raise/rescue, but I find
it reads worse if you want the equivalent of a rescue block.
This topic is locked and can not be replied to.