Techmago
Techmago

Reputation: 380

Send email to all users in rails

I am trying to create a method that, when called send a email to all users.

My ultimate goal is to call this method via a scheduler (i already got the scheduler working) And the method will go thought all users and send emails to some of then if some pre-requisites are met.

Right now i just want to learn how i make a simplest stuff that is to send a custom email to every user in the table.

My first issue is:

  def send_digest
    @users = User.all
    @users.each do |user|
      @time  = Time.now
      mail(to: user.email, subject: user.name)
    end
  end

This method (is inside app/mailer/user_mailer.rb) only is sending one e-mail to the guy with biggest ID in the table. Why that?

Also, what i need to do to access the variable "user.name" inside the email?

EDIT: There a better way for accessing user variable inside the mail body than doing @user = user?

  def send_digest(user)
    @time  = Time.now
    @user = user
    mail(to: user.email, subject: 'mail message')
  end

Upvotes: 2

Views: 1616

Answers (1)

Sully
Sully

Reputation: 14943

For each call to the mailer method one email is sent

in scheduled worker

def calling_method
   @users.each do |user|
     send_digest(user.email, user.name)
   end
end

in user mailer

def send_digest(user_email, user_name)
   mail(to: user_email, subject: user_name)
end

Upvotes: 3

Related Questions