Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - abandon sending mail within ActionMailer action

I'm wondering how I could conditionally abandon sending mail within the action ActionMailer action itself.


class SomeMailer < ActionMailer::Base
  ...

  def some_emails
    some_models = Model.where(:a => 1)
    if !some_models.blank?
      mail(...)
    else
      # What to add here?
      # render :nothing => true doesn't work
    end
  end

end

Now invoking this through SomeMailer.some_emails.deliver! returns an ArgumentError: A sender (Return-Path, Sender or From) required to send a message

like image 235
tamersalama Avatar asked Dec 15 '10 16:12

tamersalama


2 Answers

Set perform_deliveries to false, like so:

emails = get_email_list_somehow
if emails.present?
  mail options.merge(:bcc => emails)
else
  self.message.perform_deliveries = false
end

This will quietly not try to send and should stop the error from happening.

like image 54
Jack Dempsey Avatar answered Sep 21 '22 15:09

Jack Dempsey


In Rails 3.2.9 you can finally conditionally call mail(). Here's the related GitHub thread. Now the OP's code can be reworked like this:

class SomeMailer < ActionMailer::Base
  ...

  def some_emails
    some_models = Model.where(:a => 1)
    unless some_models.blank?
      mail(...)
    end
  end

end
like image 30
Bozhidar Batsov Avatar answered Sep 20 '22 15:09

Bozhidar Batsov