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
Click the compose box, after composing your message, click on BCC and add all your recipients. This will send the emails to the recipients keeping email addresses hidden from each other.
Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from ActionMailer::Base and live in app/mailers. Those mailers have associated views that appear alongside controller views in app/views.
Go to the config folder of your emails project and open environment. rb file and add the following line at the bottom of this file. It tells ActionMailer that you want to use the SMTP server. You can also set it to be :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux.
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. :(
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With