Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Actionmailer Sending Multiple Recipients

I'm having trouble getting Rails to send an email to multiple users at once. I am trying to send a notification to multiple venues signed up to my site when an Enquiry that matches them is approved.

A pending Enquiry has to be approved by admin. The mailer is passed the @enquiry, which is when the email is triggered. Shown here in my Enquiries controller:

def approve
    @enquiry.approve
    redirect_to [:admin, @enquiry], notice: 'Enquiry is approved.'
    SupplierMailer.new_enquiry(@enquiry).deliver
 end

In my Supplier_mailer.rb, I have this method:

    def new_enquiry(enquiry)
      @enquiry = enquiry
      @enquiry.venues.each do |venue|
        mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
      end
    end

Currently, it is only sending to 1 email address, so not looping properly.

Models:

Enquiry 
  has_and_belongs_to_many :venues

Supplier
  has_many :venues
  has_one :user

What have I done wrong?

Thanks

like image 806
Ralph King Avatar asked Jan 16 '14 10:01

Ralph King


People also ask

What is action mailer?

Action Mailer is the Rails component that enables applications to send and receive emails. In this chapter, we will see how to send an email using Rails. Let's start creating an emails project using the following command. tp> rails new mailtest. This will create the required framework to proceed.


1 Answers

The new_enquiry method is supposed to build one email, which is then being send with deliver method. The loop work correctly, however every time you're calling mail, you override its previous call, and the method returns the last call.

Instead, first get the list of recipients, and use it as a to attribute

emails = @enquiry.venues.map {|venue| venue.supplier.user.email}
mail(to: emails, subject: 'You have a new enquiry')

If you are not happy with sending other emails to each other, you will need place Mailer action inside the loop:

def approve
  @enquiry.approve
  redirect_to [:admin, @enquiry], notice: 'Enquiry is approved.' 
  @enquiry.venues.each do |venue|
    SupplierMailer.new_enquiry(@enquiry, venue).deliver
  end
end

def new_enquiry(enquiry, venue)
  @enquiry = enquiry
  mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
end

Final option is pretty hacky, but provides best interface:

class SupplierMailer << ActionMailer::Base

  def self.new_enquiry(enquiry)
    @enquiry = enquiry
    mails = @enquiry.venues.map do |venue|
      mail(to: venue.supplier.user.email, subject: 'You have a new enquiry')
    end
    class << mails
      def deliver
        each(&:deliver)
      end
    end
    mails
  end
like image 123
BroiSatse Avatar answered Nov 10 '22 10:11

BroiSatse