DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Rails Email Mailer Daemon

02.05.2008
| 775 views |
  • submit to reddit
        Simple email mailer using the daemon module.

#!/usr/bin/env ruby

RAILS_ENV = ARGV[1] || 'development'

require 'Daemon'
require File.dirname(__FILE__) + '/../../config/environment.rb'

if RAILS_ENV == "test"
  SLEEP_TIME = 10
else
  SLEEP_TIME = 60
end

class Mailer < Daemon::Base
  
  def self.start
    puts "Starting Mailer Daemon"
    
    sendmail_settings = { :location => '/usr/sbin/sendmail', :arguments => '-i -t -f [your email address]' }
    
    loop do

      emails = Email.find( :all, :conditions => [ 'send_after <= ? and sent_at is not null', Time.now.strftime( "%Y-%m-%d %H:%M:%S" ) ], :limit => 500 )
      unless emails.empty?
        
        emails.each do | _email |
          
          email = TMail::Mail.new
          email.to = _email.email_to
          email.from = _email.email_from
          email.subject = _email.email_subject
          email.date = Time.now
          email.mime_version = '1.0'
          email.set_content_type 'text', 'plain', { 'charset' => 'UTF8' }
          email.body = _email.email_body
          
          IO.popen( "#{ sendmail_settings[ :location ] } #{ sendmail_settings[:arguments] }", "w+" ) do | sm |
            sm.print( email.encoded.gsub( /\r/, '' ) )
            sm.flush
          end
          
          File.open( 'mail_log.log', 'a' ) do | file |
            file.write( email.encoded.gsub( /\r/, '' ) )
          end
          
          email.sent_at = Time.now
          email.save
          
        end
        
      end
      
      sleep(SLEEP_TIME)
    end
  end
  
  def self.stop
    puts "Stopping Mailer Daemon"
  end
end

Mailer.daemonize