How to include ActionMailer class in rake task?
Asked Answered
S

2

12

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.

Snipes answered 30/1, 2014 at 12:42 Comment(0)
J
10

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
Jubilation answered 30/1, 2014 at 12:54 Comment(2)
But how do I include preview of my webpage here in my mail?Snipes
In views/user_mailer/test_email.text.erb in the example aboveJubilation
S
9

From your tag, I believe you're using Rails.

You can load your Rails environment by requiring a dependency to the environment task as follows:

task :my_task => :environment do
    ...
end

instead of

task :my_task do
    ...
end

Let me know if it helps.

Spine answered 30/1, 2014 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.