Handle mail server problems

I'm making a rails application that regularly sends out e-mails to users. While testing recently a controller got a timeout when trying to send an e-mail. => the mail server was down.

Is there an easy way to handle something like this? Or do I have to handle a timeout-exception whereever sending of mail is initiated?

I'm grateful for any help!

The best way is probably to have a queue that you store your emails in and then have a cron job to deliver them. I use railmail and modified it to work as a queue instead of immediately deliver the emails.

You can wrap it in a timeout block also. It goes something like

Timeout::timeout(10) do   #send your email with a 10 second timeout end

rescue Timeout::Error #log the error

Thanks Fredrik

Thanks! I think that timeout solution will do just fine. I agree that the best thing would be to put the e-mails into a queue, but in my app the e-mails are sendt as notifications, and must be sent immediately.

Eivind Løland-Andersen wrote:

The best way is probably to have a queue that you store your emails in and then have a cron job to deliver them. I use railmail and modified it to work as a queue instead of immediately deliver the emails.

You can wrap it in a timeout block also. It goes something like

Timeout::timeout(10) do   #send your email with a 10 second timeout end

rescue Timeout::Error #log the error

Thanks! I think that timeout solution will do just fine. I agree that the best thing would be to put the e-mails into a queue, but in my app the e-mails are sendt as notifications, and must be sent immediately.

You can send them immediately in a background process that can try several times if a timeout occurs before giving up. Take a look at http://wiki.rubyonrails.org/rails/pages/HowToRunBackgroundJobsInRails

I've tried ap4r and backgroundrb. Both are not very well documented, however I found it easier to cope with ap4r.

btw - as an alternative, try activemessaging - I use it for exactly this problem: http://code.google.com/p/activemessaging/ Cheers, -A

Even though most mail servers use queues that does not mean they don't immediately try to deliver email. You really are better off letting the mail server handle it rather than write your own mail server in Ruby.