Search code examples
ruby-on-railsruby-on-rails-4actionmailerrails-apirails-console

actionmailer works in console but not in controller


I am using action mailer in a production heroku environment. When I run the console like so:

heroku run console
FamilyMailer.notify_family_member(FamilyMember.last)

It works perfectly and sends the email. However, when I write the EXACT SAME line in a controller, It doesn't seem to activate the mailer. The puts statement in the mailer doesn't even appear in the console. Here is the controller action:

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

Here is the event model:

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

Here is the mailer:

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

Here are the server logs:

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

As you can see, the model method is being called but the mailer is just being ignored. I've also tried changing .deliver to .deliver_now but that does not help.

How do I fix this?


Solution

  • The deliver method, should be called at the Mailer method. But instead of using deliver, use deliver_now or deliver_later.

    Change your controller to:

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

    And your mailer:

    class FamilyMailer < ApplicationMailer
      default from: "Gold<[email protected]>"
      def notify_family_member(family_member)
        puts "in the mailer"
        mail(to: family_member.email, subject: "Photos")
      end
    end