Skip to content

Instantly share code, notes, and snippets.

@maxivak
Last active January 22, 2024 17:51
Show Gist options
  • Save maxivak/8460f022f5b369626069 to your computer and use it in GitHub Desktop.
Save maxivak/8460f022f5b369626069 to your computer and use it in GitHub Desktop.
Send email to multiple recipients in Rails with ActionMailer

Send email to multiple recipients

Send multiple emails to different recipients.

Mailer class

# app/mailers/notify_mailer.rb

class NotifyMailer < ApplicationMailer
  default from: '[email protected]'

  def self.send_request(row)
    emails = ['[email protected]', '[email protected]']
    
    emails.each do |email|
      new_request(email,row).deliver_now
      # or
      #new_request(email,row).deliver_later
      
    end
  end

  def new_request(email, row)
    @item = row

    mail(to: email, subject: 'New request')

  end
end

Send email

row = Request.find(1)
NotifyMailer.send_request(row)

This will send several separate emails.

Email content

# app/views/notify_mailer/new_request.html.erb

<br>
New callback request
<br>
phone: <%=@item.phone %><br>
name: <%=@item.name %><br>
email: <%=@item.email %><br>
notes: <%=@item.notes %><br>
date: <%=@item.created_at %><br>

# app/views/notify_mailer/new_request.txt.erb

New callback request
===============================================
<br>
phone: <%=@item.phone %><br>
name: <%=@item.name %><br>
email: <%=@item.email %><br>
notes: <%=@item.notes %><br>
date: <%=@item.created_at %><br>

WRONG WAY

if you have this

class NotifyMailer < ApplicationMailer
  default from: '[email protected]'

  def new_request(email, row)
    @item = row
   
    emails = ['[email protected]', '[email protected]']
    
    emails.each do |email|
      mail(to: email, subject: 'New request : ')
    end
  end

And you run

row = Request.find(1)
NotifyMailer.new_request(row).deliver_now

This will try to send ONE email containing all emails for every recipient.

This is WRONG SOLUTION.

@vfonic
Copy link

vfonic commented Jun 16, 2020

Would the second solution send one email with all the people in CC or where would that email go?

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment