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

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

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文件中使用简单邮件命令? 或者我是否必须安装任何gem?

请帮忙。 谢谢。

一个非常丑陋但有用的方法从ruby做同样的事情:

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

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

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