如何在rake任务中包含ActionMailer类? [英] How to include ActionMailer class in rake task?

查看:81
本文介绍了如何在rake任务中包含ActionMailer类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的rake任务中使用ActionMailer,以便在特定时间向人们发送电子邮件。

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

我在app / mailers文件夹中编写了一个邮件程序类,如下所示:

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

class AlertsMailer < ActionMailer::Base
  default from: 'x@y.com'

  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

然后在我的rake任务中包括以下行:

Then I included the following line in my rake task:

AlertsMailer.mail_alert(email_addresses, subject)

当我尝试运行rake任务时:

When I try to run the rake task:

rake update_db

我得到以下内容错误:

uninitialized constant AlertsMailer

我认为我必须以某种方式在我的rake任务中加载mailer类,但是我不知道该怎么做。

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.

请帮助。

推荐答案

我有以下内容,它是工作:

I have the following and it is working:

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

# 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 => "default_sender@foo.bar") do |format|
        format.text(:content_type => "text/plain", :charset => "UTF-8", :content_transfer_encoding => "7bit")
      end
    end
  end
end

这篇关于如何在rake任务中包含ActionMailer类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆