abcreddy abcreddy - 6 months ago 14
Ruby Question

how to use linux 'mail' command from a ruby file to send a mail?


In the below code, I have to send an e-mail on the status of the process whether it is completed, error out or timed out...

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


In general, we use linux 'mail' command only in .sh files not in the .rb files. Below is how we write the 'mail' command to send mails in .sh files.

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


Is there any way to use the simple mail command in the .rb file? Or do I have to install any gems for the same?

Please Help.
Thank you.

Answer

A really ugly but useful way to do the same from ruby:

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