I’m not only new to Rails, but to development in general, so I apologize if this is a basic question. I have an app where I want to send mass emails (ie newsletter) to users that opt-in. I have two concerns: (1) is my code the most efficient way to process a mass mail (ie do I need to use a for…each statement) and (2) I read other posts on Stack Overflow talking about the importance of the mail server and using delayed jobs to send email.
Other things to note:
- I’m on Heroku
- I was thinking about using SendGrid
- I added delayed job code based on this tutorial
My questions are:
- Do most people use delayed jobs even for single recipient emails (ie a user registration confirmation)?
- Is my code the most efficient way to do a mass email?
- If, for example, there’s 1000 users. Does it make a big difference in resources (ie bandwidth, CPU, etc) if I send everyone the same email with a BCC. If so, do I just pass in a hash to the mailer (ie delete the for…each and change opt_in_user parameter to @opt_in_users) and change the recipient to bcc?
Thanks!
Controller
commmunity_users = UserCommunityRelation.find('community_id = ? and status = ?,' current_community, "approved" )
@opt_in_users = User.find('opt_in = ?,' true)
@opt_in_users.each do |opt_in_user|
UserMailer.send_later(:deliver_announcement, opt_in_user)
end
UserMailer.rb
def announcement(opt_in_user)
mail(:to => "#{opt_in_user.username} <#{opt_in_user.email}>", :subject => "Huge Announcement!")
end
For bulk sending, you should definitely send it via a service (We use Postbox, SendGrid is another option). In addition to the load on the servers, a service will also probably be better suited to bounces, spam blockers, etc, and it will probably offer extra benefits, such as tracking.
For single user emails, I would go with direct emails in the controller.
You wouldn’t want to have a controller action manage queueing the tasks, as it will affect your sites responsiveness. Use a cron job and rake task to do it in the background.
I think BCC is fine on resource usage, but your server will be getting hit with any bounces, and it is an extra service to manage, hence, I’d go with a service as mentioned earlier
BTW, for the #each vs for…each question, the cost of the iterator is going to be so low that it isn’t worth thinking about IMO.