actionmailer 在控制台中工作,但在控制器中不工作

actionmailer works in console but not in controller

我在生产 heroku 环境中使用 action mailer。当我 运行 控制台像这样时:

heroku run console
FamilyMailer.notify_family_member(FamilyMember.last)

它完美运行并发送了电子邮件。但是,当我在控制器中写入完全相同的行时,它似乎并没有激活邮件程序。邮件程序中的 puts 语句甚至没有出现在控制台中。这是控制器操作:

def create
  puts "in the create action"
  @event = Event.find(params[:event_id])
  @event.notify_family_members  #from Event model called below
end

事件模型如下:

class Event < ActiveRecord::Base
    def notify_family_members
        puts "in model method"
        FamilyMailer.notify_family_member(FamilyMember.last)
    end
end

这是邮件:

class FamilyMailer < ApplicationMailer
  default from: "Gold<contact@goldyo.me>"
  def notify_family_member(family_member)
    puts "in the mailer"
    mail(to: family_member.email, subject: "Photos").deliver
  end
end

服务器日志如下:

2016-04-26T20:00:07.110616+00:00 app[web.1]: Started POST "/api/events" for 69.46.236.36 at 2016-04-26 20:00:07 +0000
2016-04-26T20:00:07.231857+00:00 app[web.1]: Processing by Api::EventsController#create as HTML
2016-04-26T20:00:07.231967+00:00 app[web.1]:   Parameters: {"event_id"=>7, "event_attendees"=>{"1"=>"Larry Ellison"}, "event"=>{}}
2016-04-26T20:00:07.242261+00:00 app[web.1]: in the create action
2016-04-26T20:00:07.444983+00:00 app[web.1]: in model method
2016-04-26T20:00:07.462242+00:00 app[web.1]: [active_model_serializers] Rendered ActiveModel::Serializer::Null with Event (0.81ms)
2016-04-26T20:00:07.463231+00:00 app[web.1]: Completed 200 OK in 231ms (Views: 9.4ms | ActiveRecord: 26.9ms)
2016-04-26T20:00:07.462845+00:00 heroku[router]: at=info method=POST path="/api/events" host=goldenowl.herokuapp.com request_id=d6aeb940-a65a-4667-be1c-263bee9ef899 fwd="69.46.236.36" dyno=web.1 connect=0ms service=359ms status=200 bytes=824

如您所见,正在调用模型方法,但只是忽略了邮件程序。我也试过将 .deliver 更改为 .deliver_now 但这没有帮助。

我该如何解决这个问题?

deliver 方法,应在 Mailer 方法中调用。但是不要使用 deliver,而是使用 deliver_nowdeliver_later.

将您的控制器更改为:

def create
    FamilyMailer.notify_family_member(FamilyMember.last).deliver_now
end

还有你的邮寄者:

class FamilyMailer < ApplicationMailer
  default from: "Gold<contact@goldyo.me>"
  def notify_family_member(family_member)
    puts "in the mailer"
    mail(to: family_member.email, subject: "Photos")
  end
end