Search code examples
ruby-on-railsherokurakemailer

Rake mailer task only sends newsletter to last subscriber


Last night I found out my rake mailer task that sends my newsletter, only sends it to the last subscriber. But why?! I use Heroku Scheduler to perform the task.

This is my code in scheduler.rake:

desc "This task is called by the Heroku scheduler add-on"
task :send_newsletter => :environment do
  if Time.now.saturday?
    NewsletterMailer.weekly_best.deliver
  end
end

This is how I defined weekly_best in my NewsletterMailer:

def weekly_best
  @subscriptions = NewsletterSubscription.where(active: true)

  @plugins = Plugin.where("created_at >= ?", Date.today.beginning_of_week).where("cached_votes_up > ?", 0).order(:cached_votes_up => :desc).first(5)

  @subscriptions.each do |s|
    mail(to: s.email, from: "Great Wavelengths <[email protected]>", subject: "Weekly best gear")
  end
end

As you can see I do iterate over all the email addresses of the subscriptions, but then why does it not send it to everyone?

Hope you guys can help :)


Solution

  • The method NewsletterMailer.weekly_best will return only the last email from your @subscriptions.each loop. Then you call deliver on this one single email, and that is why only one email is sent.

    To fix it you need to call deliver on each mail separately. You could do something like this:

    class NewsletterMailer
      def self.deliver_weekly_best
        subscriptions = NewsletterSubscription.where(active: true)
        plugins = Plugin.where(...)
    
        # Call deliver for each subscription   
        subscriptions.each { |sub| weekly_best(sub, plugins).deliver } 
      end
    
      def weekly_best(sub, plugins)
        @plugins = plugins
        mail(to: sub.email, ...)
      end
    end
    

    Then in your schedule you just do:

    NewsletterMailer.deliver_weekly_best