Permalink
Browse files

add email class to send emails to users for forgotten passwords

  • Loading branch information...
1 parent 84a1344 commit f525fc8fef514d316ecca5412ac54bd73b61562b @dusty committed Jul 20, 2011
Showing with 79 additions and 0 deletions.
  1. +10 −0 init.rb
  2. +69 −0 models/email.rb
View
10 init.rb
@@ -18,6 +18,16 @@
MongoMapper.database.authenticate(ENV['MONGO_USER'], ENV['MONGO_PASS'])
end
+## Setup Email options
+SMTP_OPTS = {
+ :address => ENV['SMTP_HOST'],
+ :user_name => ENV['SMTP_USER'],
+ :password => ENV['SMTP_PASS'],
+ :port => ENV['SMTP_PORT'],
+ :authentication => ENV['SMTP_AUTH'],
+ :domain => ENV['SMTP_DOMAIN'] || 'localhost.localdomain'
+}
+
# Require sinatra apps
Dir["./models/*.rb"].sort.each {|req| require req}
Dir["./app/*.rb"].sort.each {|req| require req}
View
69 models/email.rb
@@ -0,0 +1,69 @@
+class Email
+ include MongoMapper::Document
+
+ key :recipients, Array
+ key :subject, String
+ key :message, String
+ key :sent_at, Time
+ key :error_msg, String
+ timestamps!
+
+ ensure_index :sent_at
+ ensure_index :recipients
+
+ validates_presence_of :subject, :message
+ validate :validate_recipients
+
+ def self.pending
+ where(:sent_at => {"$exists" => false})
+ end
+
+ ## Sendgrid headers
+ def headers
+ {
+ 'X-SMTPAPI' => {
+ 'to' => recipients,
+ 'category' => 'agentpocket'
+ }.to_json
+ }
+ end
+
+ def delivered?
+ !sent_at.blank?
+ end
+
+ def deliver_once
+ deliver unless delivered?
+ end
+
+ def deliver
+ begin
+ Pony.mail(
+ :from => "alerts@#{site.domain}",
+ :to => recipients.first,
+ :subject => "[#{site.title}] #{subject}",
+ :body => message,
+ :headers => headers,
+ :via => :smtp,
+ :via_options => SMTP_OPTS
+ )
+ update_attributes(:sent_at => Time.now.utc)
+ rescue StandardError => e
+ update_attributes(:error_msg => "#{e.class} : #{e.message}")
+ puts "#{e.class} : #{e.message}\n#{e.backtrace}\n"
+ end
+ end
+
+ protected
+
+ def site
+ @site ||= Site.default
+ end
+
+ def validate_recipients
+ errors.add(:recipients, 'are invalid') unless recipients.all? do |recipient|
+ Validator.valid_email?(recipient)
+ end
+ end
+
+end

0 comments on commit f525fc8

Please sign in to comment.