无法在 Rails 4.2 任务上从 Ruby 发送邮件

Unable to send mail from Ruby on Rails 4.2 task

我可以从 rails 控制台发送邮件,但是 rake 任务没有发送相同的邮件

这是我的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
  }

邮寄者:

class ScriptAlertMailer < ApplicationMailer

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

任务:

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

正在 rails console 发送邮件。无论是在开发环境还是生产环境加载:

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

在 log/[environment].log 中输出呈现的邮件程序视图,然后发送。

但是当我使用 rake inspect_js 执行此操作时,没有任何内容附加到日志并且未发送

我试过 deliver, deliver!, deliver_later and deliver_now 但没有成功

有什么想法吗?

deliver 方法不应在邮件程序本身内调用。在 rails 控制台中,您看到了 Mail::Message 对象,但我认为没有发送任何实际的电子邮件。下面的更改应该可以使您的任务正常工作。

在邮件程序中,更改:

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

收件人:

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

在rake任务中,更改:

ScriptAlertMailer.alert_email "mymail@domain.com"

收件人:

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