ruby-on-railsrubyactionmailerrake-task

Rails rake task that loops through multiple email recipients without using bcc


I have a Rails rake task that I'm using to send emails and the only way I can get my Mailer to send to multiple recipients is by collecting them in the Mailer and then listing them as bcc recipients like this:

class SubscribersMailer < ApplicationMailer
  def send_daily_updates
    @subscribers = Subscriber.all
    recipients = @subscribers.collect(&:email).join(",")

    @subscribers.each do |subscriber|
      mail(to: "***@example.com.com", subject: "Email subject", :bcc => recipients)
    end
  end
end

And in my task, I'm just calling this:

SubscribersMailer.send_daily_updates.deliver_now

When I run the rake task it successfully sends the email to each address, but this doesn't seem like the ideal way to do this. Sending out mass emails with a bunch of addresses in the bcc field is a good way to get it marked as spam.

What is a better way to loop through the recipients? Should I do this in the rake task or in the Mailer?


Solution

  • I advice you to use only one subscriber in mailer and call it for each subscriber at the rake task. Like

    class SubscribersMailer < ApplicationMailer
      def send_daily_updates(subscriber)
        mail(to: subscriber.email, subject: "Email subject")
      end
    end
    
    Subscriber.find_each do |subscriber|
      SubscribersMailer.send_daily_updates(subscriber).deliver_now
    end
    

    This will generate a bunch of emails, but subscribers will see only their email address in received letter. That is more secure (you not expose all of you subscribers email addresses to each subscriber) and get lower risk that it will be marked as spam.

    Also I advice you to use some background workers instead of rake tasks (Sidekiq, Rescue, and etc.)