-3

Possible Duplicate:
how to keep sending emails to users every week depending on user date input in rails

I am building a system that allows a user to insert info name, date, and email. I want the system to automatically send emails to its users every 7 days from which they inserted.

here`s my mailer

class UserMailer < ActionMailer::Base
  default from: "from@example.com"
   def welcome_email(dop)
    @dop = dop
    @url  = "http://example.com/login"
    mail(:to => dop.mail, :subject => "Welcome to My Awesome Site")
  end
end

and this is controller:

def create
    @dop = Dop.new(params[:dop])

    respond_to do |format|
      if @dop.save
        UserMailer.welcome_email(@dop).deliver
        format.html { redirect_to @dop, notice: 'Dop was successfully created.' }
        format.json { render json: @dop, status: :created, location: @dop }
      else
        format.html { render action: "new" }
        format.json { render json: @dop.errors, status: :unprocessable_entity }
      end
    end
  end
Jason Aller
  • 3,541
  • 28
  • 38
  • 38

2 Answers2

3

You need to write a rake task and call that task through cron.

For example:

task :send_email => :environment do
  Dop.where('last_email <= ?', 7.days.ago).each do |dop|
    UserMailer.welcome_email(dop).deliver
    dop.update_attribute('last_email', Time.now)
  end
end

Now set up your machines Cron scheduler to call this Rake task every few minutes to send out emails automatically.

Cron is a Unix scheduler that executes programs in pre-determined intervals.

You need to edit the crontab file using crontab -e and enter something like this:

*/5 * * * *  /bin/bash cd <path_to_your_app> && rake send_email

The */5 * * * * says that you run it every 5 minutes.

Tigraine
  • 23,358
  • 11
  • 65
  • 110
0

Look for a gem called whenever

It does exactly what you want.

Kleber S.
  • 8,110
  • 6
  • 43
  • 69