namespace :epaper do task :send_email => :environment do paper = Paper.where(:ready_to_send => true).first rescue nil if !paper.nil? subscribers = Subscriber.all emails = [] mail_limit = 25 subscribers.each do |subscriber| emails << subscriber.email subscriber.last_paper_sent = paper.id.to_s subscriber.save if emails.count == mail_limit puts "Sending #{mail_limit} mails" email = Email.new(:mail_subject => paper.title, :mail_lang => :zh_tw, :template => "admin/e_papers/emailer", :template_data => {"paper" => paper}, :mail_to => emails) email.deliver emails = [] sleep 0.5 end end if !emails.empty? puts "Sending last emails" email = Email.new(:mail_subject => paper.title, :mail_lang => :zh_tw, :template => "admin/e_papers/emailer", :template_data => {"paper" => paper}, :mail_to => emails) email.deliver end paper.ready_to_send = false paper.mailed = true paper.save end end end