Search code examples
ruby-on-railsemailruby-on-rails-4rake

Unable to send mail from Ruby on Rails 4.2 task


I can deliver a mailer from rails console, but the same mailer is not being sent from a rake task

This is my environments/development.rb

  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.default_url_options = { host: 'localhost:3000' }
  config.action_mailer.smtp_settings = {
    address: 'my.mail.server',
    port: 465,
    user_name: "my-account",
    password: "my-password",
    athentication: :plain,
    ssl: true
  }

Mailer:

class ScriptAlertMailer < ApplicationMailer

  def alert_email(to)
    mail(to: to, subject: 'This is an alert').deliver
  end  
end

Task:

task :inspect_js => :environment do
  puts "running inspect_js"
  ScriptAlertMailer.alert_email "mymail@domain.com"
end

The mail is being sent in rails console. No matter whether loaded in development or production environments:

ScriptAlertMailer.alert_email "an-account@domain.com"

Outputs the rendered mailer view in log/[environment].log then is sent.

But when I do it with rake inspect_js nothing is appended to log and is not sent

I've tried with deliver, deliver!, deliver_later and deliver_now with no luck

Any thoughts?


Solution

  • The deliver method should not be called within the mailer itself. In rails console, you are seeing the Mail::Message object, but I don't think any actual email is being sent. The changes below should get your task to work.

    In the mailer, change:

    mail(to: to, subject: 'This is an alert').deliver
    

    To:

    mail(to: to, subject: 'This is an alert')
    

    In the rake task, change:

    ScriptAlertMailer.alert_email "mymail@domain.com"
    

    To:

    ScriptAlertMailer.alert_email("mymail@domain.com").deliver_now