延迟工作和行动邮件

Dan*_*min 4 ruby-on-rails actionmailer delayed-job

我在使用ActionMailer实现延迟作业时遇到问题:在延迟执行作业之前:

class NotificationsMailer < ActionMailer::Base

  default :from => "noreply@mycompany.com"
  default :to => "info@mycompany.com"

  def new_message(message)
    @message = message
    mail(:subject => "[Company Notification] #{message.subject}")
  end

end
Run Code Online (Sandbox Code Playgroud)

并使用此行调用它(它工作得非常好):

NotificationsMailer.new_message(@message).deliver
Run Code Online (Sandbox Code Playgroud)

在延迟工作实施后,我所做的就是将交付线更改为:

NotificationsMailer.delay.new_message(@message)
Run Code Online (Sandbox Code Playgroud)

另外,我使用了启动作业队列

rake jobs:work
Run Code Online (Sandbox Code Playgroud)

我可以看到数据库中的对象,如果作业已关闭,我可以看到它们在我启动工作后弹出但没有任何反应(没有发送电子邮件).

更新 - 其他延迟任务(与邮件无关)工作正常.

任何人都可以帮助新手吗?

提前致谢!!

Dhi*_*raj 5

我花了很多时间使用延迟的工作发送电子邮件,最后它可以工作.

在宝石文件中

gem 'delayed_job'
gem 'delayed_job_active_record'
Run Code Online (Sandbox Code Playgroud)

在控制器中

 def dtest

    UserMailer.delay.welcome_email
    render json:"Succes"
    return
 end
Run Code Online (Sandbox Code Playgroud)

在邮件中

class UserMailer < ActionMailer::Base
  default from: "from@example.com"

  def welcome_email
    ActionMailer::Base.delivery_method = :smtp 
        ActionMailer::Base.smtp_settings = {
                address: "smtp.gmail.com", 
                port: 587, 
                domain: 'gmail.com',
                Authentication: "plain", 
                enable_starttls_auto: true, 
                user_name: 'your@gmail.com',
                password: 'yourpassword'
            }

    mail(to: 'no-reply@gmail.com', subject: 'Background Email Test').deliver

  end

end
Run Code Online (Sandbox Code Playgroud)

在此之后,我只需启动rails服务器并开始工作

rake jobs:work
Run Code Online (Sandbox Code Playgroud)

我希望,它会帮助你们和电子邮件发送使用"延迟工作":)