module MailSpy module Manager # ------------------------------------------- ADD_TEMPLATE # Programmatically add email templates with a schema of search and # replaceable text # def add_template(name, html_erb, text_erb, template_values_definition) MailSpy::EmailTemplate.create!( { :name => name, :html_erb => html_erb, :text_erb => text_erb, :template_values_definition => template_values_definition }) end # ------------------------------------------- ADD INSTANCE # Adds a instance of a email template to the queue to send # def add_instance(options) options.to_options! required_options = [ :template_name, :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 "add_instance call missing #{ro}" unless options.include? ro } # 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 we have a template options[:template_name] template = MailSpy::EmailTemplate.first(conditions: {name: options[:template_name]}) raise "No template: #{options[:template_name]} found, try add_template first" unless template # 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.email_template = template 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| MailSpy::CoreMailer.template(email).deliver email.update_attribute(:sent, true) sent += 1 end offset += step end sent end # ------------------------------------------- TRACKING # def track_other_action end end end