Tuesday, October 6, 2009

Rails ActionMailer gmail Configuration using SMTP

If u have RAILS_VERSION >= 2.3.3 and RUBY VERSION >= 1.8.7

then you no need to install any tls plugin.... Just follow the below steps....


Step 1

You have to add the following Configuration settings in {RAILS_ROOT}/config/environment.rb for Gmail ..


config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "YourmailID@gmail.com",
:password => "password123",
:authentication => :login,
:enable_starttls_auto => true #This line is must to ensure the tls for Gmail
}
config.action_mailer.default_content_type = "text/html"

Step2
Create mailer for your Project

#Type this in terminal
script/generator mailer
for eg.,

$ script/generator mailer Mailnotifier
exists app/models/
create app/views/mailnotifier
exists test/unit/
create test/fixtures/mailnotifier
create app/models/mailnotifier.rb
create test/unit/mailnotifier_test.rb


Step 3
Then you need to generate the mailer method for describing the mail content etc.,

$ script/generate mailer Mailnotifier notifier
exists app/models/
exists app/views/mailnotifier
exists test/unit/
exists test/fixtures/mailnotifier
overwrite app/models/mailnotifier.rb? (enter "h" for help) [Ynaqdh] Y
force app/models/mailnotifier.rb
overwrite test/unit/mailnotifier_test.rb? (enter "h" for help) [Ynaqdh] Y
force test/unit/mailnotifier_test.rb
create app/views/mailnotifier/notifier.erb
create test/fixtures/mailnotifier/notifier

Step 4
Then your models/Mailnotifier.rb looks like

#models/Mailnotifier.rb

class Mailnotifier < ActionMailer::Base
def notifier(sent_at = Time.now)
subject 'Notifier'
recipients 'mailertest@gmail.com' # Give the recipients mailID
from 'somemail@gmail.com'
sent_on sent_at
body :greetings => 'Hi,'
end
end

Step 5
In views/mailnotifier/notifier.erb file you can format the mail content as you like....

You Type this in your Terminal change directory to your rails application

$ script/console
Loading development environment (Rails 2.3.4)
>> Mailnotifier.deliver_notifier


This will send You the mail to your recipients address... :)

It Works Cool for me.....