e-mail with mailgun and rails not sent to all users

Question!

I am trying to send all users an email every time a blog post is posted. Mailgun seems to deliver the email but always just to one user. I am running this in production.

my code in the mailer is this

 def new_record_notification(users)
      @users = User.all
        @users.each do |user| 
            mail to: user.email, subject: "Success! You did it."
        end
      end
    end

pins_controller.rb

 # POST /pins
  # POST /pins.json
  def create
    @pin = current_admin.pins.new(pin_params)

    respond_to do |format|
      if @pin.save
        ModelMailer.new_record_notification(@record).deliver
        format.html { redirect_to @pin, notice: 'Pin was successfully created.' }
        format.json { render action: 'show', status: :created, location: @pin }
      else
        format.html { render action: 'new' }
        format.json { render json: @pin.errors, status: :unprocessable_entity }
      end
    end
  end


Answers

I think this will resolve your problem.

mailer.rb

def new_record_notification(user)
  mail to: user.email, subject: "Success! You did it."
end

pins_controller.rb

def create
    @pin = current_admin.pins.new(pin_params)

    respond_to do |format|
      if @pin.save
        @users = User.all
        @users.each do |user| 
          ModelMailer.new_record_notification(user).deliver
        end
        format.html { redirect_to @pin, notice: 'Pin was successfully created.' }
        format.json { render action: 'show', status: :created, location: @pin }
      else
        format.html { render action: 'new' }
        format.json { render json: @pin.errors, status: :unprocessable_entity }
      end
    end
  end

OR

You can try following.

mailer.rb

def new_record_notification(users)
  recipients = User.all.collect{ |user| user.email }
  mail to: recipients, subject: "Success! You did it."
end

pins_controller.rb

def create
  @pin = current_admin.pins.new(pin_params)
  respond_to do |format|
    if @pin.save
      ModelMailer.new_record_notification(@record).deliver
      format.html { redirect_to @pin, notice: 'Pin was successfully created.' }
      format.json { render action: 'show', status: :created, location: @pin }
    else
      format.html { render action: 'new' }
      format.json { render json: @pin.errors, status: :unprocessable_entity }
    end
  end
end


This video can help you solving your question :)
By: admin