namespace :mail_spy do desc "Loops through the database of emails and sending those that are outstanding" task :send_outstanding_emails => :environment do step = 100 offset = 0 MailSpy::Email.limit(step).offset(offset).where(:schedule_at.lt => Time.now).all.each do |email| esp = MailSpy.esps[email.email_service_provider] esp = MailSpy.esps[rand(MailSpy.esps.count)] if esp.blank? pony_hash = {} set_if_present = Proc.new do |pony_key, email_key=nil| email_key = pony_key if email_key.nil? value = email[email_key] pony_hash[pony_key] = value if value.present? end pony_email_keys = [:to, :cc, :bcc, :from, :subject, :headers, :message_id, :sender, :reply_to] pony_email_keys.each do |key| set_if_present.call(key) end #TODO Only support smtp at the moment pony_hash[:via] = :smtp pont_hash[:via_options] = esp Pony.mail(pony_hash) email.update_attribute(:sent, true) offset += step end end end