Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 332
Slick23 Avatar asked Sep 15 '11 20:09

Slick23


People also ask

How do you send multiple cc's?

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.

What is Action mailer in Rails?

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.

How do I send an email to ROR?

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.


2 Answers

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. :(

like image 141
Chris Ledet Avatar answered Sep 19 '22 22:09

Chris Ledet


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

like image 44
raoul_dev Avatar answered Sep 16 '22 22:09

raoul_dev