This tutorial will cover how to send emails using gmail with Ruby on Rails. In my opinion this is not a good idea, for example there may be some restrictions on number of mails sent in a day, or if a problem occurs on the mail server you might not be able to send emails. Another issue that bothers me is that you have to store your email account’s username and password in a plain config file. However, in some occasions (never-ending client requests) you might have to use this approach.
First of all, we need to download and install a plugin called Action Mailer tls which was developed by Marc Chung.
After installing the plugin, lets copy smtp_gmail.rb
into config/initializers
.
Now we need a configuration file which email account information will be stored.
OK, we created our config file. Now, with your favorite text editor open that file and write your gmail username and password in it.
So far so good. We completed necessary configuration to add gmail support to our rails app. Now lets create our mailer.
If we successfully created our mailer, lets proceed to next step, creating the mailer method that sends email. Lets say we want to send a thank you message right after user registration. So we can give the name “thankyou_email” to our method.
Now, it’s time to create the template which will be used for our “thank you” email.
Lets put a few words in that template:
So close to the happy ending. Now put the following code in your controller in the method that will be responsible for sending thank you emails.
Well of course you may give another name to that method, and you may want to extend this method a little bit. For example you might want to check if the mail is sent successfully by adding a rescue block.
That’s it, we are cleared to take off! Just don’t forget to reset your rails app because plugin installations need restart as far as i know.
P.S: I used this approach with Ruby on Rails versions 2.0 and 2.1. I’m not sure if it works with older versions of rails.