module MailSpy module Manager # ------------------------------------------- CREATE EMAIL # Adds a instance of a email template to the queue to send # def create_email(options) options.to_options! required_options = [ :campaign, :stream, :component, :schedule_at, :subject, :template_values, :from, :reply_to] to_options = [:to, :cc, :bcc] # Ensure that we have the required options required_options.each { |ro| raise "create_email call missing #{ro}" unless options.include? ro } # Ensure that the campaign, stream and component are not blank # These keys are used to define the s3 paths for the templates [:campaign, :stream, :component].each { |key| raise "##{key} can't be blank" if options[key].blank? } # Make sure we have someone to send to has_sender = options.keys.select { |option| to_options.include? option.intern }.present? raise "Email instance has no sender (to,cc,bcc were all blank)" unless has_sender # Make sure that (required_options + to_options).each do |option| unless MailSpy::Email.method_defined? "#{option}=".intern raise "MailSpy::Email doesn't have #{option} as a setter '" end end email = MailSpy::Email.create!(options) email.save! email end # ------------------------------------------- SEND OUTSTANDING EMAILS # Batches through all the emails that were scheduled and have come due # sends them out (step many at a time) def send_outstanding_emails(step=100) raise "No Email service providers installed" unless MailSpy.esps.present? offset = 0 sent = 0 # Helper function for setting present values def set_if_present(email, pony_hash, pony_key, email_key=nil) email_key = pony_key if email_key.nil? value = email.send("#{email_key}") pony_hash[pony_key] = value if value.present? end while (true) mails = MailSpy::Email. limit(step).offset(offset). where(:schedule_at.lte => DateTime.now, :sent => false).all break if mails.blank? mails.each do |email| mail = MailSpy::CoreMailer.template(email) #TODO might be nice to flush mail out in debug mode mail.deliver email.update_attribute(:sent, true) sent += 1 end offset += step end sent end # ------------------------------------------- TRACKING # def track_other_action end end end