Skip to content

Instantly share code, notes, and snippets.

@DmitryBash
Forked from maxivak/readme.md
Created April 30, 2020 07:18
Show Gist options
  • Save DmitryBash/5e67a35a4136dac46ce8aa3ceaf03f9c to your computer and use it in GitHub Desktop.
Save DmitryBash/5e67a35a4136dac46ce8aa3ceaf03f9c 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.

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