Back when Rails 2.2 introduced
:enable_starttls_auto => true as default for ActionMailer configurations it broke many apps. I myself stumbled over this problem several times. It is quite easy to google for workarounds, but I always found it troubling, that those almost always advise you to turn off encryption of your smtp session and send user credentials as plain text.
Yesterday I ran into the problem again with a new Rails 3 application I am writing. After much digging around, I found out that with Rails 3 you have a new option to fix the problem that was not there in Rails 2. As I was unable to find this with Google and it took me quite some time to figure this out, I thought I would write it up here:
The Problem: By default, ActionMailer will test if your smtp server knows TLS and then try to start a TLS session using the Ruby bindings for the OpenSSL library. OpenSSL will check the server’s certificate and if it finds a problem with that raise an exception (
hostname was not match with the server certificate) .
In theory this is fine, because it is clearly a misconfiguration of the smtp server. But in practice this is annoying if a) your smtp server runs on the same host as the application and you do not want to use TLS at all or b) you do not control the server’s configuration but still want to use TLS.
Most workarounds show how to disable TLS, which is trivial, but a rather bad solution for b) as you start sending user credentials in plain text over the internet.
Fortunately, Rails 3 offers another solution: ActionMailer in Rails 3 uses the mail gem instead of the older TMail library. The mail gem offers a configuration option to disable OpenSSL’s certificate check. All of ActionMailers configuration options get passed to the mail library, so simply adding
:openssl_verify_mode => 'none'
to your ActionMailer configuration does the trick.
So now you have 3 options when you are confronted with the above exception. Please consider them in the following order:
- If you control the smtp server, go ahead, learn about TLS and configure the server properly.
- If you cannot change the smtp server’s configuration, think hard about the risk involved when accepting random certificates and if you cannot avoid it, disable certificate checking.
- If you only deliver to localhost or really, really know what you are doing, disable TLS.