Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the best way to check if email was sent once when using rake task?

I have simple mailer which sends user weekly digest and rake task which sends to all users this email, and it is pinned to heroku scheduler.

I want to send to user this email each week but only once a week, no matter how many times I run rake send_weekly_digest

Mailer

class DigestMailer < ActionMailer::Base
  include Resque::Mailer
  default from: "[email protected]"

  def weekly_digest(user_id)
    @user = User.find(user_id)

    mail :to => @user.email, :subject => "Weekly Digest"
  end
end

Rake Task

desc "Send weekly email digest"
task send_weekly_digest: :environment do
  User.all.each do |user|
    DigestMailer.weekly_digest(user.id).deliver
  end
end
like image 987
tomekfranek Avatar asked Jan 25 '26 09:01

tomekfranek


1 Answers

Add a column to your users table called last_emailed_at or something similar and then update that column with a timestamp when you send the weekly digest.

Then in your rake task instead of saying User.all, only get users that haven't been emailed in the last week:

User.where("last_emailed_at < ?", 1.week.ago)
like image 184
John Avatar answered Jan 27 '26 21:01

John