Skip to content

Instantly share code, notes, and snippets.

@radinreth
Forked from maxivak/readme.md
Created January 11, 2016 08:21
Show Gist options
  • Save radinreth/56af53b880d651d3f363 to your computer and use it in GitHub Desktop.
Save radinreth/56af53b880d651d3f363 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: 'notify@mysite.com'

  def self.send_request(row)
    emails = ['email1@mysite.com', 'email2@another.com']
    
    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: 'notify@mysite.com'

  def new_request(email, row)
    @item = row
   
    emails = ['email1@mysite.com', 'email2@another.com']
    
    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