Send to multiple recipients in Rails with ActionMailer
Solution 1:
You can just send one email for multiple recipients like this.
def request_replacement(shift)
@shift = shift
@user = shift.user
@recipients = User.where(:replacement_emails => true)
@url = root_url
emails = @recipients.collect(&:email).join(",")
mail(:to => emails, :subject => "A replacement clerk has been requested")
end
This will take all your @recipients
email addresses and join them with ,
. I think you can also pass an array to the :to
key but not sure.
The only problem is you won't be able to use @name
in your template. :(
Solution 2:
In the Rails guides (Action Mailer Basics) it says the following regarding multiple emails:
The list of emails can be an array of email addresses or a single string with the addresses separated by commas.
So both "[email protected], [email protected]"
and ["[email protected]", "[email protected]"]
should work.
See more at: http://guides.rubyonrails.org/action_mailer_basics.html
Solution 3:
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)