如何使用linux' mail'从ruby文件命令发送邮件?

时间:2013-04-04 09:16:26

标签: ruby-on-rails ruby


在下面的代码中,我必须发送一封关于流程状态的电子邮件,无论是完成,错误还是超时......

    def check_for_forecasts
   wait_until_time = Time.now + timeout.minutes
   loop do
       RAILS_DEFAULT_LOGGER.info "Checking if process has finished"
     if find_token != 0
       update_completion_status
       RAILS_DEFAULT_LOGGER.info "Process has finished"
       break
     elsif find_error != 0
       update_timed_out_field
       RAILS_DEFAULT_LOGGER.info "Process has errored"
       break
     elsif DateTime.now > wait_until_time
       update_timed_out_field
       RAILS_DEFAULT_LOGGER.info "Process has timed out"
       break
     else
       RAILS_DEFAULT_LOGGER.info "Waiting for Process to finish"
       sleep(60) # if it hasn't completed then wait 1 min and try again.
     end
    end
  end

通常,我们只在.sh文件中使用linux'mail'命令,而不是在.rb文件中。下面是我们如何编写'mail'命令来发送.sh文件中的邮件。

 mail -s "the process has been finished" abc@xyz.com<<EOM
      The process has finished successfully.    
EOM

有没有办法在.rb文件中使用simple mail命令?或者我是否必须安装任何宝石?

请帮助。 谢谢。

2 个答案:

答案 0 :(得分:2)

从红宝石中做同样的事情是一种非常丑陋但有用的方法:

to = "abc@xyz.com"
subject = "the process has been finished"
content = "The process has finished successfully."
`mail -s "#{subject}" #{to}<<EOM
  #{content}
EOM`

答案 1 :(得分:2)

您可以在Ruby中使用反引号来运行命令行指令。所以你想要的是:

`mail -s "the process has been finished" abc@xyz.com<<EOM
  The process has finished successfully.    
EOM`