Using GMail to Send Email on Ruby on Rails 2.3
I know that Rails is now on 3.2 but since some of my apps were developed under the previous version of rails, I have no choice but to work with it.

Objective


  • To use GMail or Google's server to enable email sending on your site.
  • This method should also be applicable even on your development environment aka localhost.
  • The method should work for version 2.3.8 of rails.


Specification

  • Rails 2.3 (currently I'm on 2.3.8)
  • Ruby 1.8.6
  • Gem 1.3.7

Steps

  1. First is install ambethia-smtp-tls gem for the TLS issue. If you will not install this, you might get this error:

    Net::SMTPAuthenticationError (530 5.7.0 Must issue a STARTTLS command first.

    To install:
    1. gem install ambethia-smtp-tls -v '1.1.2' --source http://gems.github.com/

  2. Next is open environment.rb and add this at the end of the file. Note that I said "end of the file" meaning it should be outside the Rails::Initializer.run block

    1. require 'smtp-tls'
    2.  
    3. ActionMailer::Base.delivery_method = :smtp
    4. ActionMailer::Base.smtp_settings = {
    5. :address => "smtp.gmail.com",
    6. :port => 587,
    7. :domain => "gmail.com",
    8. :authentication => :plain,
    9. :user_name => "gmailusername", # don't put "@gmail.com" here, replace this with your email's username
    10. :password => "gmailpawwsord", # replace with your gmail's password
    11. :enable_starttls_auto => true }

  3. Now create a mailer:

    1. ruby script/generate mailer Notifier

  4. Open app/models/notifier.rb and copy this code

    1. def sendmail(email_from, email_to, sender_name, subject, message)
    2. from email_from
    3. recipients email_to
    4. subject "Contact Form: " + subject
    5. body(:sender => email_from, :message => message, :subject => subject, :sender_name => sender_name)
    6. end

  5. Inside the folder app/views/, Create a file named sendmail.html.erb and copy the following:
    1. A message coming from <%= @sender_name + " (#{@sender})" %>
    2. <br />
    3. <br />
    4. <b>SUBJECT:</b> <%= @subject %><br/>
    5. <br />
    6. <b>MESSAGE:</b>
    7. <fieldset>
    8. <%= @message %>
    9. </fieldset>

    NOTE: You can alsoo customize it depending on the message you will sent over the email. You can use HTML tags for customizing the look of it.

  6. Configurations and layouts should now be fine. You can now call this function to any part of your controllers in order to use it. Just follow this syntax:

    1. Notifier.deliver_sendmail([EMAIL-FROM], [EMAIL-TO], [SENDER-NAME], [SUBJECT], [MESSAGE] )
    Take note that I used the word deliver_ before the model attribute.


And that should do the trick for this version of rails. You may also customize the function and layout of these code in order to get a more personal touch on it. :)


No comments :

Post a Comment