ruby-on-rails-3actionmailer

Send to multiple recipients in Rails with ActionMailer


I'm trying to send multiple emails based on a boolean value in my database. The app is a simple scheduling app and user can mark their shift as "replacement_needed" and this should send out emails to all the users who've requested to receive these emails. Trouble is, it only every seems to send to one email. Here's my current code:

 def request_replacement(shift)
      @shift = shift
      @user = shift.user
      @recipients = User.where(:replacement_emails => true).all
      @url  = root_url
      @recipients.each do |r|
        @name = r.fname
        mail(:to => r.email,
           :subject => "A replacement clerk has been requested")
      end
  end

Solution

  • I have the same problem. I don't know what is the deal is. I sidestep it by:

    instead of calling

    Mailer.request_replacement(shift).deliver 
    

    from my controller,

    I'd define a class method on the mailer, and call that. That method would then iterate through the list and call deliver "n" times. That seems to work:

    class Mailer
    
       def self.send_replacement_request(shift)
         @recipients = ...
         @recipients.each do |recipient|
           request_replacement(recipient, shift).deliver
         end
       end
    
       def request_replacement(recipient, shift)
         ...
         mail(...)
       end
    end
    

    and from the controller, call

    Mailer.send_replacement_request(shift)