Noah
Noah

Reputation: 467

Rails send e-mail in a loop

I have the snippet below running in my Rails app, but it's not iterating properly:

task.users.each do |user|
  mail(to: user.email
       from: "Company <task." + user.id + "@mail.company.com",
       subject: "Update on " + user.assignment)
end

If there's 3 users, it only sends out one e-mail. I've verified that there aren't any errors preventing it from continuing.

I can't simply pass an array of e-mails to the to option because I need to use the user's data in each iteration.

Can this be done like the above?

Upvotes: 1

Views: 734

Answers (1)

B Seven
B Seven

Reputation: 45941

You need to call the .deliver_now method.

mail(to: user.email
       from: "Company <task." + user.id + "@mail.company.com",
       subject: "Update on " + user.assignment).deliver_now

I have run into an issue where this kind of delivery doesn't work, possibly because the mail was falling out of scope.

So you may need to do something like this:

class SendWeeklySummary
  def run
    User.find_each do |user|
      UserMailer.weekly_summary(user).deliver_now
    end
  end
end

Rails Guides docs - see section 2.1.4

Upvotes: 2

Related Questions