Skip to content

Instantly share code, notes, and snippets.

@maxivak
Last active August 12, 2022 15:01
Embed
What would you like to do?
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.

@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