Search code examples
ruby-on-railsrakeactionmailer

ActionMailer loop on rake task send an extra mail every time it runs


I cannot figure this out, I have this class

class UserMailer < ActionMailer::Base
 def apps_remainder_email()
    #apps array ..which basically have 3 records in it
    apps.each do |rec||
    mail(to:  user.email, subject: 'Apps Remainder').deliver
    end
 end
end

When I try to call the above in rails console UserMailer.apps_remainder_email it is working fine and sending out three emails, but When I add this as a rake task it sends out four instead of three i.e always a duplicate of final email.

Here is my rake task

task daily: [:environment] do  
 UserMailer.apps_remainder_email.deliver
end

I think it is because I have a .deliver in my task, but without that .deliver no mails are sending at all.

  $ rake daily --trace
    ** Invoke daily (first_time)
    ** Invoke environment (first_time)
    ** Execute environment
    ** Execute daily

Solution

  • Your UserMailer class should not call deliver by itself.

    Instead your rake task should call deliver.

    So remove deliver from the UserMailer class and place the logic into your rake task:

    task daily: [:environment] do  
       apps.each do |rec||
          UserMailer.apps_remainder_email(rec).deliver
       end
    end