Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include ActionMailer class in rake task?

I want to use ActionMailer in my rake task in order to send emails to people at a particular time.

I have written a mailer class in app/mailers folder like this:

class AlertsMailer < ActionMailer::Base
  default from: '[email protected]'

  def mail_alert(email_addresses, subject, url)
    @url  = '#{url}'
    mail(to: email_addresses, subject: 'Alert') do |format|
      format.html { render '/alerts/list' }
    end
  end
end

Then I included the following line in my rake task:

AlertsMailer.mail_alert(email_addresses, subject)

When I try to run the rake task:

rake update_db

I get the following error:

uninitialized constant AlertsMailer

I think I have to somehow load the mailer class in my rake task, but I don't have any idea how to do that.

Please help.

like image 665
Joy Avatar asked Jan 30 '14 12:01

Joy


People also ask

What is ActionMailer?

1 Introduction. Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from ActionMailer::Base and live in app/mailers. Those mailers have associated views that appear alongside controller views in app/views.

What are tasks in Rails?

Rails uses a Ruby task manager called Rake to manage tasks. A task is just some repeatable code that we'll want to run from time to time. A task could theoretically do anything, whether that's running tests, creating logs, or making changes to the database.


1 Answers

I have the following and it is working:

# in lib/tasks/mailme.rake
task :mailme => :environment do
  UserMailer.test_email(1).deliver
end

And

# in app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
  def test_email(user_id)
    @user = User.find_by_id user_id

    if (@user)
      to = @user.email

      mail(:to => to, :subject => "test email", :from => "[email protected]") do |format|
        format.text(:content_type => "text/plain", :charset => "UTF-8", :content_transfer_encoding => "7bit")
      end
    end
  end
end
like image 141
Abdo Avatar answered Oct 05 '22 01:10

Abdo