Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send multiple mails in one deliver command?

I try to send multiple mails in one single .deliver command. My mailer method looks like this:

def feedback_mail
    @verteiler = ["[email protected]", "[email protected]"]
    for v in @verteiler.sort
      mail(:to => v, :subject => "Foo Bar")
    end
end

The problem is, only one mail gets send, to the last entry of the array. any advice here?

like image 632
trnc Avatar asked Jun 23 '26 09:06

trnc


1 Answers

This idea won't scale much - you'd need to implement something like Resque and workers to process sending all the emails out.

Yes, @socjopata's idea is good, but you'll really want to iterate adding them to the job queue and spawn a couple workers to process them. As per the guides, this is how to do it:

class AdminMailer < ActionMailer::Base
  default :to => ["[email protected]", "[email protected]"],
          :from => "[email protected]"

  def new_registration(user)
    @user = user
    mail(:subject => "New User Signup: #{@user.email}")
  end
end

I'd essentially hand of YourMailer.feedback_mail(<PASS ARGS HERE>).deliver to Resque-

Resque.enqueue(SendMail, <ARGS>)  # replace this in your controller

The worker would look like

#send_mail.rb
class SendMail
  @queue = :feedback_mail_queue
  def self.perform(<ARGS>) # pass these in enqueue call
    YourMailer.feedback_mail(<PASS ARGS HERE>).deliver
  end
end

As per section 2.3.4 of the Rails Guides:

It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the :to key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas.

Looking back at your attempt, FYI - this should work

def feedback_mail
    @verteiler = ["[email protected]", "[email protected]"]
    mail(:to => @verteiler, :subject => "Foo Bar")
end
like image 139
Michael De Silva Avatar answered Jun 26 '26 00:06

Michael De Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!